1. 考虑相对位置不变
  • 注意要保持数组的稳定性
  • 当数字为偶数时,把该数字接到列表的后面
class Solution:
    def reOrderArray(self, array):
        # write code here
        i = 0
        move = 0
        while i + move < len(array):
            if array[i] % 2 == 0:
                num = array.pop(i)
                array.append(num)
                move += 1
                i -= 1
            i += 1
        return array
  1. 无需考虑相对位置不变
  • 利用双指针
    class Solution:
      def exchange(self, nums: List[int]) -> List[int]:
          start = 0
          end = len(nums)-1
          while start < end:
              while nums[start]%2 == 1 and start < len(nums)-1:
                  start += 1
              while nums[end]%2 == 0 and end >= 0:
                  end -= 1
              if start < end:
                  nums[end],nums[start] = nums[start],nums[end]
                  start += 1
                  end -= 1
          return nums