-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathAdvantageShuffle.java
More file actions
36 lines (29 loc) · 838 Bytes
/
AdvantageShuffle.java
File metadata and controls
36 lines (29 loc) · 838 Bytes
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
class Solution {
// TC : O(nlogn)
// SC : O(n)
public int[] advantageCount(int[] A, int[] B) {
int len = A.length;
int[] ans = new int[len];
PriorityQueue<int[]> pq = new PriorityQueue<int[]> ((a,b) -> (b[1] - a[1]));
for(int i=0;i<len;i++){
pq.offer(new int[] {i, B[i]});
}
int low = 0;
int high = len-1;
Arrays.sort(A);
while(!pq.isEmpty()){
int[] head= pq.poll();
int maxValueInB = head[1];
int indexInB= head[0];
if(A[high] > maxValueInB){
ans[indexInB] = A[high];
high--;
} else {
// maxValueInB > = A[high]
ans[indexInB] = A[low];
low++;
}
}
return ans;
}
}