|
26 | 26 | <p> </p>
|
27 | 27 | <p><strong>Follow up:</strong> Your algorithm's time complexity must be better than <code>O(n log n)</code>, where n is the array's size.</p>
|
28 | 28 |
|
29 |
| - |
30 | 29 | ## Solutions
|
31 | 30 |
|
32 | 31 | <!-- tabs:start -->
|
|
37 | 36 | class Solution:
|
38 | 37 | def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
39 | 38 | counter = Counter(nums)
|
40 |
| - |
41 | 39 | hp = []
|
42 | 40 | for num, freq in counter.items():
|
43 | 41 | if len(hp) == k:
|
44 |
| - if freq > hp[0][0]: |
45 |
| - heapq.heappop(hp) |
46 |
| - heapq.heappush(hp, (freq, num)) |
| 42 | + heapq.heappush(hp, (freq, num)) |
| 43 | + heapq.heappop(hp) |
47 | 44 | else:
|
48 | 45 | heapq.heappush(hp, (freq, num))
|
49 |
| - |
50 |
| - return list(map(lambda t: t[1], hp)) |
| 46 | + return [t[1] for t in hp] |
51 | 47 | ```
|
52 | 48 |
|
53 | 49 | ### **Java**
|
@@ -76,6 +72,59 @@ class Solution {
|
76 | 72 | }
|
77 | 73 | ```
|
78 | 74 |
|
| 75 | +```java |
| 76 | +class Solution { |
| 77 | + public int[] topKFrequent(int[] nums, int k) { |
| 78 | + Map<Integer, Integer> counter = new HashMap<>(); |
| 79 | + for (int num : nums) { |
| 80 | + counter.put(num, counter.getOrDefault(num, 0) + 1); |
| 81 | + } |
| 82 | + PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); |
| 83 | + counter.forEach((num, freq) -> { |
| 84 | + if (pq.size() == k) { |
| 85 | + pq.offer(new int[]{num, freq}); |
| 86 | + pq.poll(); |
| 87 | + } else { |
| 88 | + pq.offer(new int[]{num, freq}); |
| 89 | + } |
| 90 | + }); |
| 91 | + return pq.stream().mapToInt(e -> e[0]).toArray(); |
| 92 | + } |
| 93 | +} |
| 94 | +``` |
| 95 | + |
| 96 | +### **C++** |
| 97 | + |
| 98 | +```cpp |
| 99 | +class Solution { |
| 100 | +public: |
| 101 | + static bool cmp(pair<int, int>& m, pair<int, int>& n) { |
| 102 | + return m.second > n.second; |
| 103 | + } |
| 104 | + vector<int> topKFrequent(vector<int>& nums, int k) { |
| 105 | + unordered_map<int, int> counter; |
| 106 | + for (auto& e : nums) ++counter[e]; |
| 107 | + priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq(cmp); |
| 108 | + for (auto& [num, freq] : counter) |
| 109 | + { |
| 110 | + if (pq.size() == k) |
| 111 | + { |
| 112 | + pq.emplace(num, freq); |
| 113 | + pq.pop(); |
| 114 | + } |
| 115 | + else pq.emplace(num, freq); |
| 116 | + } |
| 117 | + vector<int> ans; |
| 118 | + while (!pq.empty()) |
| 119 | + { |
| 120 | + ans.push_back(pq.top().first); |
| 121 | + pq.pop(); |
| 122 | + } |
| 123 | + return ans; |
| 124 | + } |
| 125 | +}; |
| 126 | +``` |
| 127 | +
|
79 | 128 | ### **...**
|
80 | 129 |
|
81 | 130 | ```
|
|
0 commit comments