-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path347.java
More file actions
79 lines (64 loc) · 2.25 KB
/
347.java
File metadata and controls
79 lines (64 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
__________________________________________________________________________________________________
sample 7 ms submission
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Comparator<Value> comparator = new Comparator<Value>() {
@Override
public int compare(Value int1, Value int2){
return -(int1.times - int2.times);
}
};
PriorityQueue<Value> heap = new PriorityQueue<>(nums.length, comparator);
Arrays.sort(nums);
int lastNum = nums[0];
int total = 0;
for(int num : nums){
if(lastNum == num){
total++;
} else {
heap.add(new Value(lastNum, total));
total = 1;
lastNum = num;
}
}
heap.add(new Value(lastNum, total));
List<Integer> ans = new ArrayList<>();
while(k > 0){
ans.add(heap.remove().num);
k--;
}
return ans;
}
class Value {
int num;
int times;
Value(int num,int times){
this.num = num;
this.times = times;
}
}
}
__________________________________________________________________________________________________
sample 36496 kb submission
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap();
for(int i=0;i<nums.length;i++){
if(!map.containsKey(nums[i]))
map.put(nums[i], 1);
else
map.put(nums[i], map.get(nums[i])+1);
}
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
System.out.println(list);
Collections.sort(list, (a,b)-> b.getValue()-a.getValue());
System.out.println(list);
List<Integer> temp = new ArrayList<>();
for(int i=0;i<k;i++){
temp.add(list.get(i).getKey());
}
System.out.println(temp);
return temp;
}
}
__________________________________________________________________________________________________