# 283 move zeroes

### 思路一：暴力

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = 0
while 0 in nums:
nums.remove(0)
i += 1
nums.extend([0]*i)


### 思路二：

0   1   0   3   12



1   1   0   3   12


1   3   0   3   12


class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
cur,idx = 0,0
while idx < len(nums):
# cur is not 0
if nums[idx] != 0 :
nums[cur] = nums[idx]
cur += 1
idx += 1

while cur < len(nums):
nums[cur] = 0
cur += 1



### 思路三：

http://fisherlei.blogspot.com/2015/10/leetcode-move-zeroes-solution.html

此法最快，beats 90.50%

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
p0, p1 = 0, 0  # P1指向非0，p0指向0
while p0 < len(nums) and p1 < len(nums):
if nums[p0] != 0:
p0 += 1
p1 = p0
continue
if nums[p1] == 0:
p1 += 1
continue
nums[p0],nums[p1] = nums[p1],nums[p0]
p0 += 1
p1 += 1


### 思路四：

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort(key= lambda x: 1 if x == 0 else 0)


timsort can require a temp array containing as many as N//2 pointers, which means as many as 2*N extra bytes on 32-bit boxes.


apachecn/AiLearning