题目

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
image.png

思路

双指针。一个指向头,一个指向尾。遍历的时候,交换,使得前面为奇数,后面为偶数。时间复杂度O(n)。

代码

  1. class Solution:
  2. def exchange(self, nums: List[int]) -> List[int]:
  3. ptr = 0
  4. tail = len(nums) - 1
  5. while ptr < tail:
  6. # 向前移动,至到指向偶数
  7. while nums[ptr] & 1 == 1 and ptr < tail:
  8. ptr += 1
  9. # 向后移动,至到指向奇数
  10. while nums[tail] & 1 != 1 and ptr < tail:
  11. tail -= 1
  12. # 交换当前指针的两个数
  13. if tail > ptr:
  14. nums[ptr], nums[tail] = nums[tail], nums[ptr]
  15. return nums