使用单步移动k的数组元素?
假设我们有一个数组,其中的n个元素从1到n按随机顺序排列。给出另一个整数K。他们正在排队的N人打羽毛球。前两个玩家将参加比赛,然后输家将在排行榜的最后排位。获胜者将与队列中的下一个人一起玩,依此类推。他们将一直玩到有人连续赢得K次为止。然后,该玩家成为赢家。
如果队列是[2,1,3,4,5]且K=2,则输出将为5。现在看说明-
(2,1)出局,2获胜,因此将1添加到队列中,Queue就像[3,4,5,1](2,3)出局,3获胜,因此2将添加到队列中,队列就像[4,5,1,2,2](3,4)播放,4胜,所以3将被添加到队列中,队列就像[5,1,2,3](4,5)播放,5胜,所以4将被添加到队列中,Queue就像[1、2、3、4](5,1)播放,5胜,所以3将被添加到队列中,Queue像[2,3,4,1]
(2,1)出局,2获胜,因此1将被添加到队列中,Queue就像[3,4,5,1]
(2,3)出局,3胜,所以2将被添加到队列中,Queue就像[4,5,1,2]
(3,4)出局,4胜,所以3将被添加到队列中,Queue就像[5,1,2,3]
(4,5)出局,5获胜,因此4将被添加到队列中,队列类似于[1,2,3,4]
(5,1)出局,5获胜,因此3将被添加到队列中,Queue类似于[2,3,4,1]
因为5赢得了两个连续比赛,那么输出为5。
算法
优胜者(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 player End
示例
#include <iostream> 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 < n; i++) { //for each member of the array if (arr[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 << winner(arr, n, k); }
输出结果
3