LeetCode 347.前k个高频元素

给你一个字符串 s,找到 s 中最长的回文子串。

 

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。

示例 2:

输入:s = "cbbd"
输出:"bb"

示例 3:

输入:s = "a"
输出:"a"

示例 4:

输入:s = "ac"
输出:"a"

 

提示:

  • 1 <= s.length <= 1000
  • s 仅由数字和英文字母(大写和/或小写)组成
Related Topics
  • 字符串
  • 动态规划
  • 👍 3931
  • 👎 0
  • import java.util.*;
    
    public class TopKFrequentElements{
    	public static void main(String[] args) {
    		Solution solution = new TopKFrequentElements().new Solution();
    		
    	}
    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
    		Map<Integer,Integer> map = new HashMap<>();
    		for (int num : nums) {
    			map.put(num, map.getOrDefault(num,0)+1);
    		}
    
    		Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
    
    		PriorityQueue<Map.Entry<Integer,Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
    
    		for (Map.Entry<Integer, Integer> entry : entries) {
    			queue.offer(entry);
    			System.out.println(queue);
    			if(queue.size() > k){
    				queue.poll();
    			}
    		}
    
    		int res[] = new int[k];
    
    		for (int i = 0; i < k; i++) {
    			res[i] = queue.poll().getKey();
    		}
    
    		return res;
    	}
    }
    //leetcode submit region end(Prohibit modification and deletion)
    
    }
    
    posted @ 2021-08-12 14:00  皮使我快乐  阅读(26)  评论(0)    收藏  举报