按奇偶排序数组 II
难度:
标签:
题目描述
Given an array of integers nums
, half of the integers in nums
are odd, and the other half are even.
Sort the array so that whenever nums[i]
is odd, i
is odd, and whenever nums[i]
is even, i
is even.
Return any answer array that satisfies this condition.
Example 1:
Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Example 2:
Input: nums = [2,3] Output: [2,3]
Constraints:
2 <= nums.length <= 2 * 104
nums.length
is even.- Half of the integers in
nums
are even. 0 <= nums[i] <= 1000
Follow Up: Could you solve it in-place?
代码结果
运行时间: 24 ms, 内存: 17.9 MB
解释
方法:
这个题解的思路是首先遍历原数组,将奇数和偶数分别存储在两个列表中。然后,按照题目要求,依次从两个列表中取出一个奇数和一个偶数,交替放入新的列表中,最后返回这个新列表。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
题解中假设了奇数和偶数的数量严格相等,但如果输入数据不满足这个条件(尽管题目保证了这一点),这个解法还会有效吗?
▷🦆
在题解的实现中,如果原数组中的奇数或偶数的顺序有特定的要求,使用这种方法重新排序后,原始顺序是否会被保留?
▷🦆
在实际的实现中,使用了extend方法来交替添加元素到结果列表,为什么不选择使用append方法逐个添加元素,这样做有什么优势或劣势?
▷