LeetCode_35 Move Zeroes

题目描述:

1
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

输入样例:

1
2
3
4
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Code:
方法一:统计0的个数—>前边删除0后边添加0

1
2
3
4
5
6
7
8
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in range(nums.count(0)):
nums.remove(0)
nums.append(0)

方法二:这个方法比上面复杂一些,因为这个方法还可以保证被删掉的0这个node被移到list后面,因此可以保证指针和0的相对位置也不变。因为在python的list里面,0是一个Node对象形式存储的。PS:对于这道题,倒是没必要考虑这么复杂。

1
2
3
4
5
6
7
8
9
10
11
12
13
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i, nums_len = 0, len(nums)
while i < nums_len:
if nums[i] == 0:
tmp = nums.pop(i)
nums.append(tmp)
nums_len -= 1
else:
i += 1