当前位置:网站首页>Leetcode 2164. Sort odd and even subscripts separately (yes, once)

Leetcode 2164. Sort odd and even subscripts separately (yes, once)

2022-06-12 23:35:00 I'm not xiaohaiwa~~~~

 Insert picture description here
I'll give you a subscript from 0 The starting array of integers nums . Rearrange according to the following rules nums The value in :

  1. Press Non-increasing Sequential arrangement nums Odd subscript All values on .

    • for instance , If before sorting nums = [4,1,2,3] , After sorting the values of odd subscripts, it becomes [4,3,2,1] . Odd subscript 1 and 3
      The values of are rearranged in non increasing order .
  2. Press The decreasing Sequential arrangement nums Even subscript All values on .

    for instance , If before sorting nums = [4,1,2,3] , After sorting the values of even subscripts, it becomes [2,1,4,3] . Even subscript 0 and 2 The values of are rearranged in non decreasing order .

Return rearrangement nums The array formed after the value of .

Example 1:

 Input :nums = [4,1,2,3]
 Output :[2,3,4,1]
 explain :
 First , Rearrange in ascending non odd order (1  and  3) Value .
 therefore ,nums  from  [4,1,2,3]  Turn into  [4,3,2,1] .
 then , Rearrange even subscripts in non decreasing order (0  and  2) Value .
 therefore ,nums  from  [4,1,2,3]  Turn into  [2,3,4,1] .
 therefore , The array formed after rearrangement is  [2,3,4,1] .

Example 2:

 Input :nums = [2,1]
 Output :[2,1]
 explain :
 Because there is only one odd subscript and one even subscript , So there will be no rearrangement .
 The resulting array is  [2,1] , Just like the initial array . 
 

Tips :

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Code:

class Solution {
    
public:
    vector<int> sortEvenOdd(vector<int>& nums) {
    
        vector<int>even;
        vector<int>odd;
        for(int i=0;i<nums.size();i++)
        {
    
            if(i%2)
            {
    
                odd.push_back(nums[i]);
            }
            else
                even.push_back(nums[i]);
        }
        sort(odd.begin(),odd.end(),greater<int>());
        sort(even.begin(),even.end());
        vector<int>res;
        for(int i=0;i<even.size();i++)
        {
    
            res.push_back(even[i]);
            if(i<(odd.size()))
            res.push_back(odd[i]);
        }
        return res;
    }
};
原网站

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