当前位置:网站首页>Sorting odd and even subscripts respectively for leetcode simple problem

Sorting odd and even subscripts respectively for leetcode simple problem

2022-07-06 15:07:00 ·Starry Sea

subject

I'll give you a subscript from 0 The starting array of integers nums . Rearrange according to the following rules nums The value in :
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 .
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
source : Power button (LeetCode)

Their thinking

   Thanks to the python Convenient slicing , We can sort elements with even subscripts and elements with odd subscripts separately .

class Solution:
    def sortEvenOdd(self, nums: List[int]) -> List[int]:
        nums[::2]=sorted(nums[::2])
        nums[1::2]=sorted(nums[1::2],reverse=True)
        return nums

 Insert picture description here

原网站

版权声明
本文为[·Starry Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131327152804.html