LeetCode-347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
算法复杂度不符合要求
public List<Integer> topKFrequent(int[] nums, int k) {//排序 map my List<Integer> res = new ArrayList<Integer>(); Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for (int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])){ map.put(nums[i],map.get(nums[i])+1); } else{ map.put(nums[i],1); } } for (int i = 0; i <k ; i++) { int max=0; int value = 0; for (Map.Entry entry:map.entrySet()) { if((Integer)entry.getValue()>max){ max = (Integer)entry.getValue(); value = (Integer)entry.getKey(); } } res.add(value); map.put(value,0); } return res; }
桶排序
堆排序