LeetCode347 出现频率最高的K个元素

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) {
        List<Integer>[] bucket = new ArrayList[nums.length + 1];
        HashMap<Integer,Integer> fMap = new HashMap<Integer,Integer>();
        for(int n : nums){
            fMap.put(n, fMap.getOrDefault(n, 0) + 1);
        }
        for(int key : fMap.keySet()){
            int frequency = fMap.get(key);
            if (bucket[frequency] == null) {
			bucket[frequency] = new ArrayList<>();
		}
            bucket[frequency].add(key);
        }
        List<Integer> res = new ArrayList<>();
        for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
		if (bucket[pos] != null) {
			res.addAll(bucket[pos]);
		}
	}
	return res;
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/84980957