LeetCode 题解工作台
对奇偶下标分别排序
给你一个下标从 0 开始的整数数组 nums 。根据下述规则重排 nums 中的值: 按 非递增 顺序排列 nums 奇数下标 上的所有值。 举个例子,如果排序前 nums = [4, 1 ,2, 3 ] ,对奇数下标的值排序后变为 [4, 3 ,2, 1 ] 。奇数下标 1 和 3 的值按照非递增…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们可以将奇数下标和偶数下标分别取出来,然后对奇数下标的数组进行非递增排序,对偶数下标的数组进行非递减排序,最后再将两个数组合并即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。根据下述规则重排 nums 中的值:
- 按 非递增 顺序排列
nums奇数下标 上的所有值。- 举个例子,如果排序前
nums = [4,1,2,3],对奇数下标的值排序后变为[4,3,2,1]。奇数下标1和3的值按照非递增顺序重排。
- 举个例子,如果排序前
- 按 非递减 顺序排列
nums偶数下标 上的所有值。- 举个例子,如果排序前
nums = [4,1,2,3],对偶数下标的值排序后变为[2,1,4,3]。偶数下标0和2的值按照非递减顺序重排。
- 举个例子,如果排序前
返回重排 nums 的值之后形成的数组。
示例 1:
输入:nums = [4,1,2,3] 输出:[2,3,4,1] 解释: 首先,按非递增顺序重排奇数下标(1 和 3)的值。 所以,nums 从 [4,1,2,3] 变为 [4,3,2,1] 。 然后,按非递减顺序重排偶数下标(0 和 2)的值。 所以,nums 从 [4,1,2,3] 变为 [2,3,4,1] 。 因此,重排之后形成的数组是 [2,3,4,1] 。
示例 2:
输入:nums = [2,1] 输出:[2,1] 解释: 由于只有一个奇数下标和一个偶数下标,所以不会发生重排。 形成的结果数组是 [2,1] ,和初始数组一样。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 100
解题思路
方法一:排序
我们可以将奇数下标和偶数下标分别取出来,然后对奇数下标的数组进行非递增排序,对偶数下标的数组进行非递减排序,最后再将两个数组合并即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
a = sorted(nums[::2])
b = sorted(nums[1::2], reverse=True)
nums[::2] = a
nums[1::2] = b
return nums
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) due to sorting two separate lists of up to n/2 elements each. Space complexity is O(n) for storing the even and odd lists before merging back into the array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can you separate values by index type before sorting?
- question_mark
What happens if you mix odd and even index elements during sorting?
- question_mark
How does your approach maintain the pattern while sorting independently?
常见陷阱
外企场景- error
Sorting the entire array without separating indices causes incorrect order.
- error
Failing to handle single-element even or odd positions may produce errors.
- error
Merging incorrectly by index can overwrite values and break the desired pattern.
进阶变体
外企场景- arrow_right_alt
Sorting odd indices in ascending order instead of descending.
- arrow_right_alt
Handling arrays with duplicate values at the same index type.
- arrow_right_alt
Sorting indices independently for multi-dimensional arrays or subarrays.