Find the Winner of an Array Game

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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值