1996. The Number of Weak Characters in the Game
T: O(nlogn + n)
S: O(n)class Solution {
public int numberOfWeakCharacters(int[][] properties) {
Arrays.sort(properties, (a, b) -> {
if (a[0] == b[0]) {
return b[1] - a[1];
}
return a[0] - b[0];
});
Deque<Integer> stack = new ArrayDeque<>();
int result = 0;
for (int[] property : properties) {
while (!stack.isEmpty() && property[1] > stack.peek()) {
stack.pop();
result++;
}
stack.push(property[1]);
}
return result;
}
}
/*
[[1,1],[2,1],[2,2],[1,2]]
[1,1], [1,2],[2,1],[2,2]
sort attack first, fix one value
then use mono stack, decreasing, if larger than peak, get the weak one
but if attack equals, how we get the right ans?
ex:
[1,1], [1,2] -> in this case, we should not pop [1,1], because attack equals
the tricks is do the when attack equals, do defense sort by desc
-> become
[1,2], [1,1] -> in this way, it wont pop, it's correct
T: O(nlogn + n)
S: O(n)
*/jausing Heap
Last updated
Was this helpful?