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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class Solution { Map<Integer, Integer> map = new HashMap<>(); public int getWinner(int[] arr, int k) { LinkedList<Integer> list = new LinkedList<>(); int max = -100000000; for (int i = 0; i < arr.length; i++) { list.add(arr[i]); max = Math.max(max, arr[i]); }
boolean bool = true; int result = -100000000; while (bool) { int i = list.get(0); int j = list.get(1); if (i == max || j == max) { return max; } if (i > j) { exchange(list, 1); if (map.getOrDefault(i, 0) + 1 == k) { bool = false; result = i; } map.put(i, map.getOrDefault(i, 0) + 1); }else { exchange(list, 0); if (map.getOrDefault(j, 0) + 1 == k) { bool = false; result = j; } map.put(j, map.getOrDefault(j, 0) + 1); } } return result; }
public void exchange(LinkedList<Integer> list, int index){ int i = list.pollFirst(); int j = list.pollFirst(); if (index == 0) { list.offerLast(i); list.offerFirst(j); }else { list.offerLast(j); list.offerFirst(i); } } }
|