Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 660ed84

Browse files
committed
solve problem Top K Frequent Elements
1 parent 2847082 commit 660ed84

File tree

5 files changed

+137
-0
lines changed

5 files changed

+137
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ All solutions will be accepted!
315315
|71|[Simplify Path](https://leetcode-cn.com/problems/simplify-path/description/)|[java/py/js](./algorithms/SimplifyPath)|Medium|
316316
|451|[Sort Characters By Frequency](https://leetcode-cn.com/problems/sort-characters-by-frequency/description/)|[java/py/js](./algorithms/SortCharactersByFrequency)|Medium|
317317
|215|[Kth Largest Element In An Array](https://leetcode-cn.com/problems/kth-largest-element-in-an-array/description/)|[java/py/js](./algorithms/KthLargestElementInAnArray)|Medium|
318+
|347|[Top K Frequent Elements](https://leetcode-cn.com/problems/top-k-frequent-elements/description/)|[java/py/js](./algorithms/TopKFrequentElements)|Medium|
318319

319320
# Database
320321
|#|Title|Solution|Difficulty|
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Top K Frequent Elements
2+
We can solve this problem by heap and hashmap
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
class Frequency {
3+
int value;
4+
int frequency;
5+
6+
Frequency(int value, int frequency) {
7+
this.value = value;
8+
this.frequency = frequency;
9+
}
10+
}
11+
12+
public List<Integer> topKFrequent(int[] nums, int k) {
13+
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
14+
for (int num : nums) {
15+
if (frequencyMap.get(num) == null)
16+
frequencyMap.put(num, 1);
17+
else
18+
frequencyMap.put(num, frequencyMap.get(num) + 1);
19+
}
20+
21+
Comparator<Frequency> frequencyComparator = new Comparator<Frequency>() {
22+
public int compare(Frequency a, Frequency b) {
23+
return a.frequency > b.frequency ? -1 : (a.frequency == b.frequency ? 0 : 1);
24+
}
25+
};
26+
Queue<Frequency> queue = new PriorityQueue<Frequency>(frequencyComparator);
27+
for (int key : frequencyMap.keySet()) {
28+
queue.add(new Frequency(key, frequencyMap.get(key)));
29+
}
30+
31+
List<Integer> res = new ArrayList<Integer>();
32+
for (int i = 0; i < k; i++)
33+
res.add(queue.poll().value);
34+
return res;
35+
}
36+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
var topKFrequent = function(nums, k) {
7+
let frequencyMap = new Map()
8+
nums.forEach(num => {
9+
if (!frequencyMap.has(num))
10+
frequencyMap.set(num, 1)
11+
else
12+
frequencyMap.set(num, frequencyMap.get(num) + 1)
13+
})
14+
15+
let maxHeap = new MaxHeap()
16+
for (let [key, value] of frequencyMap.entries())
17+
maxHeap.push(key, value)
18+
19+
let res = []
20+
for (let i = 0; i < k; i++)
21+
res.push(maxHeap.pop())
22+
return res
23+
};
24+
25+
function MaxHeap() {
26+
this.heap = []
27+
};
28+
29+
MaxHeap.prototype.push = function(item, priority) {
30+
this.heap.push({item, priority})
31+
let pos = this.heap.length - 1,
32+
pPos = (pos % 2 == 0 ? pos - 2 : pos - 1) / 2
33+
34+
while (pPos >= 0 && priority > this.heap[pPos].priority) {
35+
let temp = this.heap[pos]
36+
this.heap[pos] = this.heap[pPos]
37+
this.heap[pPos] = temp
38+
pos = pPos
39+
pPos = (pos % 2 == 0 ? pos - 2 : pos - 1) / 2
40+
}
41+
};
42+
43+
MaxHeap.prototype.size = function() {
44+
return this.heap.length
45+
};
46+
47+
MaxHeap.prototype.pop = function() {
48+
let size = this.size()
49+
if (size == 0)
50+
throw new Error('pop form empty list')
51+
else if (size == 1)
52+
return this.heap.pop().item
53+
54+
let item = this.heap[0].item,
55+
pos = 0,
56+
maxChildPos = pos * 2 + 2
57+
this.heap[0] = this.heap.pop()
58+
59+
if (maxChildPos < size - 1)
60+
maxChildPos = this.heap[maxChildPos].priority > this.heap[maxChildPos - 1].priority ? maxChildPos : maxChildPos - 1
61+
else
62+
maxChildPos = maxChildPos - 1 < size - 1 ? maxChildPos - 1 : pos
63+
64+
while (maxChildPos < size - 1 && this.heap[pos].priority < this.heap[maxChildPos].priority) {
65+
let temp = this.heap[maxChildPos]
66+
this.heap[maxChildPos] = this.heap[pos]
67+
this.heap[pos] = temp
68+
pos = maxChildPos
69+
maxChildPos = pos * 2 + 2
70+
71+
if (maxChildPos < size - 1)
72+
maxChildPos = this.heap[maxChildPos].priority > this.heap[maxChildPos - 1].priority ? maxChildPos : maxChildPos - 1
73+
else
74+
maxChildPos = maxChildPos - 1 < size - 1 ? maxChildPos - 1 : pos
75+
}
76+
77+
return item
78+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution(object):
2+
def topKFrequent(self, nums, k):
3+
"""
4+
:type nums: List[int]
5+
:type k: int
6+
:rtype: List[int]
7+
"""
8+
frequency_map = {}
9+
for num in nums:
10+
if not frequency_map.get(num):
11+
frequency_map[num] = 1
12+
else:
13+
frequency_map[num] += 1
14+
15+
heap = []
16+
for key, value in frequency_map.items():
17+
heap.append({ 'value': key, 'frequency': value })
18+
19+
return [x['value'] for x in heapq.nlargest(k, heap, lambda e : e['frequency'])]
20+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /