-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathComparator question
More file actions
97 lines (73 loc) · 2.36 KB
/
Copy pathComparator question
File metadata and controls
97 lines (73 loc) · 2.36 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Solution {
public String frequencySort(String s) {
// ArrayList<Character> a1=new ArrayList<>();
// ArrayList<Integer> a2=new ArrayList<>();
HashMap<Character,Integer> map=new HashMap<>();
for(int i=0;i<s.length();i++)
{
// if(!a1.contains(s.charAt(i)))
// {
// a1.add(s.charAt(i));
// a2.add(1);
// }
// else{
// a2.set(a1.indexOf(s.charAt(i)),a2.get(a1.indexOf(s.charAt(i)))+1);
// }
map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
}
// PriorityQueue<Character> pq = new PriorityQueue<>((a,b) -> a2.get(a1.indexOf(b)) - a2.get(a1.indexOf(a)));
PriorityQueue<Character> pq = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a));
pq.addAll(map.keySet());
String ans="";
while(!pq.isEmpty())
{
char c=pq.poll();
int m=map.get(c);
while(m>0)
{
ans=ans+c;
m--;
}
}
return ans;
}
}
# Priority Queue with comparator declaration
PriorityQueue<Integer> pq=new PriorityQueue<Integer>(new Comparator<Integer>()
{
public int compare(Integer a, Integer b)
{
if(map.get(a)==map.get(b))
{
return a-b;
}
else{
return map.get(a)-map.get(b);
}
}
});
# Sorting Array using comparator(Example)
class Solution {
public int[][] kClosest(int[][] p, int k) {
int ans[][]=new int[k][2];
PriorityQueue<int[]> pq = new PriorityQueue<>((n1, n2) -> n1[0]*n1[0] + n1[1]*n1[1] - n2[0]*n2[0] - n2[1]*n2[1]);
for (int[] temp : p)
{
pq.add(temp);
}
for (int i = 0; i < k; i++){
ans[i] = pq.poll();
}
return ans;
}
}
# IF-ELSE inside Arrays.sort
Arrays.sort(v, (a,b)->{
if(a[0]==b[0])
{
return a[1]-b[1];
}
else{
return a[0]-b[0];
}
});