原題
分割一個整數(shù)數(shù)組,使得奇數(shù)在前偶數(shù)在后。
給定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。
解題思路
- 非常相似的題[Partition Array]
- 正宗兩個指針中對撞型指針的問題
- 最外層大while循環(huán),終止條件是兩根指針對撞
- 內(nèi)層循環(huán),分三步走
- 左邊如果是奇數(shù), left++
- 右邊如果是偶數(shù), right--
- 最后停下時如果left <= right, swap
完整代碼
class Solution:
# @param nums: a list of integers
# @return: nothing
def partitionArray(self, nums):
if not nums:
return nums
left, right = 0, len(nums) - 1
while left <= right:
while left <= right and nums[left] % 2 == 1:
left += 1
while left <= right and nums[right] % 2 == 0:
right -= 1
if left <= right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1