LeetCode 题解工作台
按奇偶排序数组 II
给定一个非负整数数组 nums , nums 中一半整数是 奇数 ,一半整数是 偶数 。 对数组进行排序,以便当 nums[i] 为奇数时, i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数 。 你可以返回 任何满足上述条件的数组作为答案 。 示例 1: 输入: nums = [4,…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们用两个指针 和 分别指向偶数下标和奇数下标,初始时 $i = 0$, $j = 1$。 当 指向偶数下标时,如果 是奇数,那么我们需要找到一个奇数下标 ,使得 是偶数,然后交换 和 。继续遍历,直到 指向数组末尾。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个非负整数数组 nums, nums 中一半整数是 奇数 ,一半整数是 偶数 。
对数组进行排序,以便当 nums[i] 为奇数时,i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数 。
你可以返回 任何满足上述条件的数组作为答案 。
示例 1:
输入:nums = [4,2,5,7] 输出:[4,5,2,7] 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
示例 2:
输入:nums = [2,3] 输出:[2,3]
提示:
2 <= nums.length <= 2 * 104nums.length是偶数nums中一半是偶数0 <= nums[i] <= 1000
进阶:可以不使用额外空间解决问题吗?
解题思路
方法一:双指针
我们用两个指针 和 分别指向偶数下标和奇数下标,初始时 , 。
当 指向偶数下标时,如果 是奇数,那么我们需要找到一个奇数下标 ,使得 是偶数,然后交换 和 。继续遍历,直到 指向数组末尾。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
n, j = len(nums), 1
for i in range(0, n, 2):
if nums[i] % 2:
while nums[j] % 2:
j += 2
nums[i], nums[j] = nums[j], nums[i]
return nums
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a candidate's understanding of two-pointer techniques and their ability to maintain invariant conditions during an array traversal.
- question_mark
Evaluate the candidate's familiarity with array manipulation and in-place swapping as an optimization technique.
- question_mark
Assess how the candidate balances time complexity and space constraints in their approach.
常见陷阱
外企场景- error
Failing to maintain the correct parity at each index by improperly swapping or missing swaps for some elements.
- error
Incorrect handling of boundary conditions, such as when pointers exceed array limits.
- error
Using additional space for sorting unnecessarily, violating the space complexity requirement of O(1).
进阶变体
外企场景- arrow_right_alt
Handling cases with larger arrays where the time complexity becomes critical.
- arrow_right_alt
Handling edge cases with arrays where all elements are already sorted by parity.
- arrow_right_alt
Generalizing the two-pointer technique for arrays of odd length or arrays with other constraints.