-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_50.java
More file actions
81 lines (73 loc) · 2.19 KB
/
Copy pathDay_50.java
File metadata and controls
81 lines (73 loc) · 2.19 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
// Sort an Array
class Solution {
public void heapifyDown(int[] nums, int ind, int last){
int lchild = 2*ind+1, rchild = 2*ind+2, largest = ind;
if(lchild<=last && nums[lchild]>nums[largest]) largest = lchild;
if(rchild<=last && nums[rchild]>nums[largest]) largest = rchild;
if(largest != ind){
int temp = nums[ind];
nums[ind] = nums[largest];
nums[largest] = temp;
heapifyDown(nums,largest,last);
}
}
public int[] sortArray(int[] nums) {
int n = nums.length;
for(int i=n/2 - 1; i>=0; i--){
heapifyDown(nums,i,n-1);
}
int last = n - 1;
while(last > 0){
int temp = nums[last];
nums[last] = nums[0];
nums[0] = temp;
last--;
if(last>0){
heapifyDown(nums,0,last);
}
}
return nums;
}
}
// Sort Characters By Frequency
class Solution {
public String frequencySort(String s) {
int n = s.length();
Map<Character,Integer> mpp = new HashMap<>();
for(int i=0;i<n;i++){
char ch = s.charAt(i);
mpp.put(ch,mpp.getOrDefault(ch,0)+1);
}
PriorityQueue<Character> pq = new PriorityQueue<>((a,b) -> Integer.compare(mpp.get(b), mpp.get(a)));
for(var it : mpp.keySet()){
pq.offer(it);
}
StringBuilder sb = new StringBuilder();
while(!pq.isEmpty()){
char ch = pq.poll();
int freq = mpp.get(ch);
while(freq != 0){
sb.append(ch);
freq--;
}
}
return sb.toString();
}
}
// K Closest Points to Origin
class Solution {
public int[][] kClosest(int[][] points, int k) {
int n = points.length;
int[][] ans = new int[k][2];
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->Integer.compare(a[0]*a[0]+a[1]*a[1],b[0]*b[0] + b[1]*b[1]));
for(int i=0;i<n;i++){
pq.offer(points[i]);
}
int i = 0;
while(i<k && !pq.isEmpty()){
ans[i] = pq.poll();
i++;
}
return ans;
}
}