Brutal Force
class Solution(object):
def exchange(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
length = len(nums)
for i in range(length):
if nums[i] % 2 == 1:
res.insert(0, nums[i])
if nums[length - 1 - i] % 2 == 0:
res.append(nums[length - 1 - i])
return res
双指针
class Solution(object):
def exchange(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left = 0
right = len(nums) - 1
while left < right:
if nums[left] % 2 == 0 and nums[right] % 2 == 1:
temp = nums[right]
nums[right] = nums[left]
nums[left] = temp
elif nums[left] % 2 != 0 and nums[right] % 2 == 1:
left += 1
elif nums[left] % 2 == 0 and nums[right] % 2 != 1:
right -= 1
else:
left += 1
right -= 1
return nums