数组元素通过单个移动移动了k个位置?

数组元素通过单个移动移动了k个位置?

假设我们有一个数组,其中包含n个元素,从1到n的顺序被打乱。给定另一个整数K。有N个人排队打羽毛球。前两个玩家将去打球,然后失败者将去排队的末尾。胜者将与队列中的下一个人比赛,依此类推。他们将一直打球,直到有人连续赢得K次。然后该选手成为胜者。

如果队列是[2, 1, 3, 4, 5],K = 2,那么输出将是5。现在看一下解释:

(2, 1)比赛,2获胜,所以1将被添加到队列中,队列变为[3, 4, 5, 1] (2, 3)比赛,3获胜,所以2将被添加到队列中,队列变为[4, 5, 1, 2] (3, 4)比赛,4获胜,所以3将被添加到队列中,队列变为[5, 1, 2, 3] (4, 5)比赛,5获胜,所以4将被添加到队列中,队列变为[1, 2, 3, 4] (5, 1)比赛,5获胜,所以3将被添加到队列中,队列变为[2, 3, 4, 1]

(2, 1)比赛,2获胜,所以1将被添加到队列中,队列变为[3, 4, 5, 1]

(2, 3)比赛,3获胜,所以2将被添加到队列中,队列变为[4, 5, 1, 2]

(3, 4)比赛,4获胜,所以3将被添加到队列中,队列变为[5, 1, 2, 3]

(4, 5)比赛,5获胜,所以4将被添加到队列中,队列变为[1, 2, 3, 4]

(5, 1)比赛,5获胜,所以3将被添加到队列中,队列变为[2, 3, 4, 1]

由于5连续赢得两场比赛,所以输出是5。

算法

winner(arr, n, k)

Begin   if k >= n-1, then return n   best_player := 0   win_count := 0   for each element e in arr, do      if e > best_player, then         best_player := e         if e is 0th element, then            win_count := 1         end if      else         increase win_count by 1      end if      if win_count >= k, then         return best player     done   return best playerEnd

登录后复制

Example

的中文翻译为:

示例

#include using namespace std;int winner(int arr[], int n, int k) {   if (k >= n - 1) //if K exceeds the array size, then return n      return n;   int best_player = 0, win_count = 0; //initially best player and win count is not set   for (int i = 0; i  best_player) { //when arr[i] is better than the best one, update best         best_player = arr[i];         if (i) //if i is not the 0th element, set win_count as 1         win_count = 1;      }else //otherwise increase win count      win_count += 1;      if (win_count >= k) //if the win count is k or more than k, then we have got result         return best_player;   }   return best_player; //otherwise max element will be winner.}main() {   int arr[] = { 3, 1, 2 };   int n = sizeof(arr) / sizeof(arr[0]);   int k = 2;   cout 

输出

3

登录后复制

以上就是数组元素通过单个移动移动了k个位置?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2583387.html

(0)
上一篇 2025年3月6日 14:33:24
下一篇 2025年3月6日 06:55:49

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论