Sort Even and Odd Indices Independently
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
even_indices = []
odd_indices = []
# Extract values at even and odd indices
for i in range(len(nums)):
if i % 2 == 0:
even_indices.append(nums[i])
else:
odd_indices.append(nums[i])
# Sort the values
even_indices.sort()
odd_indices.sort(reverse=True)
# Place the values back into the list
for i in range(len(nums)):
if i % 2 == 0:
nums[i] = even_indices[i // 2]
else:
nums[i] = odd_indices[i // 2]
return nums
|
This solution first extracts the values at even and odd indices from the input list into two separate lists: even_indices
and odd_indices
. Then, it sorts the even_indices
list in non-decreasing order and the odd_indices
list in non-increasing order. Finally, it places these sorted values back into their original positions in the input list.