当前位置:网站首页>Leetcode 2293. Minimax game (yes. One pass)

Leetcode 2293. Minimax game (yes. One pass)

2022-06-10 14:01:00 I'm not xiaohaiwa~~~~

 Insert picture description here
I'll give you a subscript from 0 The starting array of integers nums , Its length is 2 The power of .

Yes nums Execute the following algorithm :

  1. set up n be equal to nums The length of , If n == 1 , End The algorithm process . otherwise , establish A new array of integers newNums , The length of the new array is n
    / 2 , Subscript from 0 Start .
  2. For satisfying 0 <= i < n / 2 Each even numbers Subscript i , take newNums[i] assignment by min(nums[2 * i],
    nums[2 * i + 1]) .
  3. For satisfying 0 <= i < n / 2 Each Odd number Subscript i , take newNums[i] assignment by max(nums[2 * i],
    nums[2 * i + 1]) .
  4. use newNums Replace nums .
  5. From step 1 Start repeat The whole process .

After executing the algorithm , return nums The remaining number in the .

Example 1:

 Insert picture description here

 Input :nums = [1,3,5,2,4,8,2,2]
 Output :1
 explain : Repeat the algorithm to get the following array .
 The first round :nums = [1,5,4,2]
 The second round :nums = [1,4]
 The third round :nums = [1]
1  It's the last number left , return  1 .

Example 2:

Input :nums = [3]
Output :3
explain :3 That's the last number left , return 3 .

Tips :

  • 1 <= nums.length <= 1024
  • 1 <= nums[i] <= 10^9
  • nums.length yes 2 The power of

Code:

class Solution {
    
public:
    int minMaxGame(vector<int>& nums) {
    
        do
        {
    
            int n=nums.size();
            if(n==1)
                return nums[0];
            
            vector<int>newnums;
            newnums.resize(nums.size()/2);
            copy(nums.begin(),nums.begin()+nums.size()/2,newnums.begin());
            
            
            for(int i=0;i<newnums.size();i++)
            {
    
                if((i%2)==0)
                {
    
                    int num=min(nums[2*i],nums[2*i+1]);
                    newnums[i]=num;
                }
                else
                {
    
                    int num=max(nums[2*i],nums[2*i+1]);
                    newnums[i]=num;
                }
            }
            nums=newnums;
        }while(1);
        return 0;
        
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101353451336.html