[leetcode] 1535. Find the Winner of an Array Game

网友投稿 819 2022-08-23

[leetcode] 1535. Find the Winner of an array Game

[leetcode] 1535. Find the Winner of an Array Game

Description

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 = 2Output: 5Explanation: 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 | 2So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.

Example 2:

Input: arr = [3,2,1], k = 10Output: 3Explanation: 3 will win the first 10 rounds consecutively.

Example 3:

Input: arr = [1,9,8,2,3,7,6,4,5], k = 7Output: 9

Example 4:

Input: arr = [1,11,22,33,44,55,66,77,88,99], k = 1000000000Output: 99

Constraints:

2 <= arr.length <= 10^51 <= arr[i] <= 10^6arr contains distinct integers.1 <= k <= 10^9

分析

题目的意思是:给你一个数组,第0个位置和第1个位置的数比较,较大的数放在第0个位置,较小的数放在最后,其他的数向前移动一个元素。这道题最好的解法是找规律,对与当前的元素cur,只需要在后续遍历的时候找到比他小的k个数就是符合题目条件的数了。所以遍历的时候利用cnt来统计比当前cur小的数目,初始化为0。注意当碰到比当前值大的时候,cur要重新赋值,这时候,cur应初始化为1,应该新的cur在当前已经有了一个比他小的值了哈哈哈哈。还是很巧妙的。

另一种思路就是利用队列来模拟一下该过程,deque,哈哈,有兴趣的可以琢磨一下。利用队列的代码链接给在下面了。

代码

class Solution: def getWinner(self, arr: List[int], k: int) -> int: n=len(arr) if(k>=n): return max(arr) for i in range(n): if(i==0): cur=arr[i] cnt=0 elif(cur>=arr[i]): cnt+=1 else: cur=arr[i] cnt=1 if(cnt==k): break return cur

参考文献

​​[LeetCode] Python; O(1) space; O(n) time - Single Pass​​​​[LeetCode]O(N) space time approach using deque in python. simple intuitive approach​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1539. Kth Missing Positive Number
下一篇:初入Android单元测试(android单元测试工具)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~