https://leetcode.com/problems/move-zeroes/
我的想法就是 用i 指针先寻找第一个zero,然后在j>i的范围内找第一个非zero的元素,然后进行交换,i继续移动到第一个zero,然后继续寻找j对应的第一非zero的元素。
my code:
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 i < len(nums) and nums[i] != 0:
i += 1
j = i + 1
while j < len(nums) and nums[j] == 0:
j += 1
if j > i and j != len(nums) and i != len(nums):
while True:
nums[i] = nums[j]
nums[j] = 0
i += 1
while j < len(nums) and nums[j] == 0:
j += 1
if j == len(nums):
break
http://bookshadow.com/weblog/2015/09/19/leetcode-move-zeroes/
这种解法更好
不要针对0,针对非0元素,只要用指针指向数组头,然后逐步把非0元素填到这个指针上就行了。0就自动全都到最后了
自己重写code
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i,j = 0,0
while j < len(nums):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1