Thursday, December 20, 2018

870. Advantage Shuffle

Version #1 Greedy
// Pair the max b if possible, otherwise use the smallest a
Time O(AlogA + BlogB)
Space O(B)

59.71 %
class Solution {
    public int[] advantageCount(int[] A, int[] B) {
int len = A.length;
int[] result = new int[len];
// int[0]->value, int[1]->index
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
for (int i = 0; i < len; i++) {
maxHeap.offer(new int[]{B[i], i});
}
Arrays.sort(A);
int small = 0;
int large = len - 1;
while (!maxHeap.isEmpty()) {
int[] curr = maxHeap.poll();
if (A[large] > curr[0]) {
result[curr[1]] = A[large];
large--;
} else {
result[curr[1]] = A[small];
small++;
}
}
return result;
}
}

No comments:

Post a Comment