1. 调整数组顺序使奇数位于偶数前面
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
方法一:
def exchange(nums):
res = []
i = 0
length = len(nums)
while i < length:
if nums[i] % 2 == 0:
res.append(nums[i])
else:
res.insert(0, nums[i])
i += 1
return res
方法二:
def exchange(nums):
return sorted(nums, key=lambda x: x % 2, reverse=True)
方法三:
def exchange(nums):
left = 0
right = len(nums) - 1
while left < right:
if (nums[left] & 1)!= 0:
left += 1
continue
if (nums[right] & 1)!= 1:
right -= 1
continue
temp = nums[left]
nums[left] = nums[right]
nums[right] = temp
left += 1
right -= 1
return nums