首頁  >  文章  >  後端開發  >  數組元素透過單一移動移動了k個位置?

數組元素透過單一移動移動了k個位置?

王林
王林轉載
2023-09-06 16:25:06827瀏覽

數組元素透過單一移動移動了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 player
End

Example

的中文翻譯為:

範例

#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

以上是數組元素透過單一移動移動了k個位置?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除