题目:
思路:
头尾两个指针,遇到满足条件就交换两个元素。判断奇偶可以通过位操作&1
代码:
Python
class Solution(object):
def exchange(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
start = 0
end = len(nums) - 1
while start < end:
first = nums[start] % 2
second = nums[end] % 2
if first == 1:
start += 1
if second == 0:
end -= 1
if first == 0 and second == 1:
tmp = nums[end]
nums[end] = nums[start]
nums[start] = tmp
start += 1
end -= 1
return nums