(Java)leetcode-347 Top K Frequent Elements

Title Description

[] Elements in the k th frequency
given a non-empty array of integers, where the front return high frequency k elements appear.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:

Input: nums = [1], k = 1
Output: [1]
Description:

You can always assume a given rational k, and 1 ≤ k ≤ number of different elements in the array.
Your time complexity of the algorithm must be better than O (n log n), n is the size of the array.

Thinking

Corresponding to the frequency of the digital map to appear in the memory, the time complexity of O (n)
using the bucket sort ordering frequency (to create an array, the array as a frequency standard, for different frequencies set number appears, into the corresponding array subscript), the number of buckets is n + 1, so the bucket sort time complexity is O (n)
Therefore, the total time complexity is O (n)
Here Insert Picture Description

Code

class Solution {
	public List<Integer> topKFrequent(int[] nums, int k) {

		List<Integer>[] bucket = new List[nums.length + 1];
		Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
		// 把数字与对应出现的频率存到map中
		for (int n : nums) {
			frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
		}

		// 桶排序
        // 将频率作为数组下标,对于出现频率不同的数字集合,存入对应的数组下标
		for (int key : frequencyMap.keySet()) {
			int frequency = frequencyMap.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;
	}
}

Present the results

Here Insert Picture Description

Published 143 original articles · won praise 45 · views 70000 +

Guess you like

Origin blog.csdn.net/z714405489/article/details/103163272