922. Sort Array By Parity 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 * 10^4
nums.length
is even.- Half of the integers in
nums
are even. 0 <= nums[i] <= 1000
Follow Up: Could you solve it in-place?
題目翻譯
這題是會可以個整數的陣列 nums
,其中陣列的元素會有一半是偶數一半是奇數。然後要重新排列陣列內的元素,讓 index 是奇數的時候,其值也是奇數。反之亦然。
解法解析
此體可以使用一次的迴圈去遍歷,判斷奇偶數後,重新排列。因應不同程式語言的特性,有的程式語言會需要額外的陣列來記錄排列後的結果。有的則不需要(例如 Python 和 Go)。
程式範例
Python
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
even_idx = 0
odd_idx = 1
sz = len(nums)
while even_idx < sz and odd_idx < sz:
if nums[even_idx] % 2 == 0:
even_idx += 2
elif nums[odd_idx] % 2 == 1:
odd_idx += 2
else:
nums[even_idx], nums[odd_idx] = nums[odd_idx], nums[even_idx]
even_idx += 2
odd_idx += 2
return nums
JavaScript
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortArrayByParityII = function (nums) {
let evenIdx = 0;
let oddIdx = 1;
while (evenIdx < nums.length && oddIdx < nums.length) {
if (nums[evenIdx] % 2 === 0) {
evenIdx += 2;
} else if (nums[oddIdx] % 2 === 1) {
oddIdx += 2;
} else {
let temp = nums[evenIdx];
nums[evenIdx] = nums[oddIdx];
nums[oddIdx] = temp;
evenIdx += 2;
oddIdx += 2;
}
}
return nums;
};
Go
func sortArrayByParityII(nums []int) []int {
length := len(nums)
even_idx := 0
odd_idx := 1
for even_idx < length && odd_idx < length {
if nums[even_idx]%2 == 0 {
even_idx += 2
} else if nums[odd_idx]%2 == 1 {
odd_idx += 2
} else {
nums[even_idx], nums[odd_idx] = nums[odd_idx], nums[even_idx]
}
}
return nums
}
Swift
class Solution {
func sortArrayByParityII(_ nums: [Int]) -> [Int] {
var result = [Int](repeating: 0, count: nums.count)
var even = 0
var odd = 1
for num in nums{
if num%2 == 0{
result[even] = num
even += 2
}else{
result[odd] = num
odd += 2
}
}
return result
}
}
Kotlin
class Solution {
fun sortArrayByParityII(nums: IntArray): IntArray {
val result = IntArray(nums.size)
var even = 0
var odd = 1
for (i in 0 until nums.size) {
if (nums[i].rem(2) == 0) {
result[even] = nums[i]
even += 2
} else {
result[odd] = nums[i]
odd += 2
}
}
return result
}
}