ID | Title | Difficulty | |
---|---|---|---|
Loading... |
347. Top K Frequent Elements
Medium
LeetCode
Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect
Problem
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]
Constraints:
- $1 <= nums.length <= 10^5$
- $-10^4 <= nums[i] <= 10^4$
- k is in the range [1, the number of unique elements in the array].
- It is guaranteed that the answer is unique.
Code
class Solution {
public int[] topKFrequent(int[] nums, int k) {
List<List<Integer>> buckets = new ArrayList<>();
buckets.add(new ArrayList<>());
Map<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
counts.put(num, counts.getOrDefault(num, 0) + 1);
buckets.add(new ArrayList<>());
}
for (int num : counts.keySet()) {
int count = counts.get(num);
buckets.get(count).add(num);
}
int[] res = new int[k];
for (int i = buckets.size() - 1; i > 0; i--) {
if(k <= 0) return res;
if(buckets.get(i).size() == 0) continue;
for(int num : buckets.get(i)) {
res[--k] = num;
}
}
return res;
}
}
按 <- 键看上一题!
346. Moving Average from Data Stream
按 -> 键看下一题!
348. Design Tic-Tac-Toe