leetcode2293: Big and small game (one question per day on 1.15)

Topic statement:

You are given a 0-based integer array nums whose length is a power of 2.

Performs the following algorithm on nums:

Let n be equal to the length of nums, if n == 1, terminate the algorithm process. Otherwise, create a new integer array newNums with length n / 2 and index starting at 0.
For each even subscript i satisfying 0 <= i < n / 2, assign newNums[i] to min(nums[2 * i], nums[2 * i + 1]).
For each odd subscript i satisfying 0 <= i < n / 2, assign newNums[i] to max(nums[2 * i], nums[2 * i + 1]).
Replace nums with newNums.
Repeat the entire process from step 1.
After executing the algorithm, return the remaining number in nums.

Example 1:

 

Input: nums = [1,3,5,2,4,8,2,2]
Output: 1
Explanation: Repeating the algorithm will result in the following array.
First round: nums = [1,5,4,2]
Second round: nums = [1,4]
Third round: nums = [1]
1 is the last remaining number, return 1.
Example 2:

Input: nums = [3]
Output: 3
Explanation: 3 is the last remaining number, return 3.
 

hint:

1 <= nums.length <= 1024
1 <= nums[i] <= 1e9
nums.length 是 2 的幂

Problem-solving ideas:

        Because the length of the nums.length array is a power of 2, each time the minimum or maximum value is taken, the length of the array will be shortened by half to obtain a new array length, which is also a multiple of 2.

        Define a while loop, when the number of array elements in nums is equal to 1, end the while loop and return the first element of the array nums. The nums array is traversed in the while loop, and the path array (the empty array defined before the while) is assigned to the nums array after the traversal. Perform the next cycle until the number of nums elements is equal to 1.

ps:

I am using the container as an array here, and push_back inserts elements, so each cycle needs clear()

Problem-solving code:

class Solution {
public:
    int minMaxGame(vector<int>& nums) {
        vector<int>path;
        while(nums.size()!=1)
        {
            for(int i=0;i<nums.size()/2;i++)
            {
                if(i%2==0)
                {
                int x=min(nums[2*i],nums[2*i+1]);
                path.push_back(x);
                }
                else
                {
                int x=max(nums[2*i],nums[2*i+1]);
                path.push_back(x);
                }
            }
            swap(nums,path);
            path.clear();
        }
        return nums[0];
    }
};

Guess you like

Origin blog.csdn.net/m0_63743577/article/details/128697784