classSolution {
funsortArrayByParityII(nums: IntArray): IntArray {
val even = mutableListOf<Int>()
val odd = mutableListOf<Int>()
// Separate even and odd numbers
for (num in nums) {
if (num % 2==0) {
even.add(num)
} else {
odd.add(num)
}
}
// Build result array
val result = IntArray(nums.size)
var evenIdx = 0var oddIdx = 0for (i in nums.indices) {
if (i % 2==0) {
result[i] = even[evenIdx++]
} else {
result[i] = odd[oddIdx++]
}
}
return result
}
}
defsortArrayByParityII(nums: list[int]) -> list[int]:
even = []
odd = []
# Separate even and odd numbersfor num in nums:
if num %2==0:
even.append(num)
else:
odd.append(num)
# Build result array result = [0] * len(nums)
even_idx = odd_idx =0for i in range(len(nums)):
if i %2==0:
result[i] = even[even_idx]
even_idx +=1else:
result[i] = odd[odd_idx]
odd_idx +=1return result
# Alternative one-liner approachdefsortArrayByParityII2(nums: list[int]) -> list[int]:
even = [x for x in nums if x %2==0]
odd = [x for x in nums if x %2==1]
result = []
for i in range(len(nums) //2):
result.append(even[i])
result.append(odd[i])
return result
classSolution {
public: vector<int> sortArrayByParityII(vector<int>& nums) {
int evenIdx =0; // Points to even indices
int oddIdx =1; // Points to odd indices
while (evenIdx < nums.size() && oddIdx < nums.size()) {
// Find misplaced even index (should have even number but has odd)
while (evenIdx < nums.size() && nums[evenIdx] %2==0) {
evenIdx +=2;
}
// Find misplaced odd index (should have odd number but has even)
while (oddIdx < nums.size() && nums[oddIdx] %2==1) {
oddIdx +=2;
}
// Swap misplaced elements if both found
if (evenIdx < nums.size() && oddIdx < nums.size()) {
swap(nums[evenIdx], nums[oddIdx]);
}
}
return nums;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
defsortArrayByParityII(nums: list[int]) -> list[int]:
even_idx =0# Points to even indices odd_idx =1# Points to odd indiceswhile even_idx < len(nums) and odd_idx < len(nums):
# Find misplaced even indexwhile even_idx < len(nums) and nums[even_idx] %2==0:
even_idx +=2# Find misplaced odd indexwhile odd_idx < len(nums) and nums[odd_idx] %2==1:
odd_idx +=2# Swap misplaced elements if both foundif even_idx < len(nums) and odd_idx < len(nums):
nums[even_idx], nums[odd_idx] = nums[odd_idx], nums[even_idx]
return nums