forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdvantage Shuffle.java
More file actions
31 lines (31 loc) · 904 Bytes
/
Advantage Shuffle.java
File metadata and controls
31 lines (31 loc) · 904 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
class Solution {
public int[] advantageCount(int[] A, int[] B) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int num : A) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int[] result = new int[A.length];
Arrays.fill(result, Integer.MIN_VALUE);
List<Integer> indexesNotPopulated = new ArrayList<>();
for (int i = 0; i < B.length; i++) {
Integer upper = map.higherKey(B[i]);
if (upper != null) {
result[i] = upper;
map.put(upper, map.get(upper) - 1);
if (map.get(upper) == 0) {
map.remove(upper);
}
} else {
indexesNotPopulated.add(i);
}
}
Iterator<Integer> iterator = indexesNotPopulated.iterator();
for (Integer key : map.keySet()) {
int value = map.get(key);
while (value-- > 0) {
result[iterator.next()] = key;
}
}
return result;
}
}