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
| class Solution { public int getWinner(int[] arr, int k) { int n = arr.length;
k = Math.min(n - 1, k);
Deque<Integer> deque = new LinkedList<>(); for (int num : arr) { deque.offer(num); }
int candidate = arr[0]; int candidateTimes = 0;
while (true) { int a = deque.poll(), b = deque.poll(); int max = Math.max(a, b), min = Math.min(a, b);
if (max != candidate) { candidate = max; candidateTimes = 1; } else { candidateTimes++; }
if (candidateTimes >= k) { return candidate; }
deque.addFirst(max); deque.addLast(min); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public int getWinner(int[] arr, int k) { int max = arr[0]; int times = 0;
for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; times = 0; }
times++; if (times == k) { return max; } }
return max; } }
|
References
1535. Find the Winner of an Array Game