Given an integer array arr
of distinct integers and an integer k
.
A game will be played between the first two elements of the array (i.e. arr[0]
and arr[1]
). In each round of the game, we compare arr[0]
with arr[1]
, the larger integer wins and remains at position 0
and the smaller integer moves to the end of the array. The game ends when an integer wins k
consecutive rounds.
Return the integer which will win the game.
It is guaranteed that there will be a winner of the game.
Example 1:
Input: arr = [2,1,3,5,4,6,7], k = 2 Output: 5 Explanation: Let's see the rounds of the game: Round | arr | winner | win_count 1 | [2,1,3,5,4,6,7] | 2 | 1 2 | [2,3,5,4,6,7,1] | 3 | 1 3 | [3,5,4,6,7,1,2] | 5 | 1 4 | [5,4,6,7,1,2,3] | 5 | 2 So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
思路:跟单调栈很类似,就是过来的时候比较一下,小的弹走,然后记录一下大的频率 +1,如果频率>=k 直接return,否则return stack里面的值;因为留下就是最大的; O(N);
class Solution {
public int getWinner(int[] arr, int k) {
if(arr == null || arr.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
HashMap<Integer, Integer> hashmap = new HashMap<>();
for(int i = 0; i < arr.length; i++) {
if(stack.isEmpty()) {
stack.push(arr[i]);
hashmap.put(arr[i], 0);
} else {
// not empty;
if(stack.peek() < arr[i]) {
hashmap.put(arr[i], hashmap.getOrDefault(arr[i], 0) + 1);
stack.pop();
stack.push(arr[i]);
} else {
// stack.peek() > arr[i];
hashmap.put(stack.peek(), hashmap.get(stack.peek()) + 1);
}
if(hashmap.get(stack.peek()) >= k) {
return stack.peek();
}
}
}
return stack.peek();
}
}