题目要求
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
解题思路
双指针
class Solution(object):
def exchange(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
i, j = 0, len(nums) - 1
while i < j:
while i < j and nums[i] % 2:
i += 1
while i < j and nums[j] % 2 == 0:
j -= 1
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
return nums