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. 给定一个数组nums,写一个函数将所有0移动到它的末尾,同时保持非零元素的相对顺序。
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array. Minimize the total number of operations. 您必须在不制作阵列副本的情况下就地执行此操作。 最小化操作总数。
思路:
直接使用list.remove(x)进行遍历
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
for p in nums:
if p == 0:
nums.remove(p)
nums.append(0)
else:
continue
return nums
if __name__ == "__main__":
num = [0, 1, 0, 3, 12]
print(Solution().moveZeroes(num))
网上思路https://blog.csdn.net/coder_orz/article/details/51384498
思路一: 从后向前搜索,把找到的0都移动到最后,即,将找到的0后面的非零数向前移动。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in xrange(len(nums)-1, -1, -1):
if nums[i] == 0:
for j in xrange(i+1, len(nums)):
if nums[j] != 0:
nums[j-1] = nums[j]
nums[j] = 0
思路二: 上面的算法效率太低,考虑将每个非零的数都移动到前面一个非零数的后面。 维持两个指针,慢的指针始终指向上一个非零数的后面,快指针向后扫描直至找到一个非零数,将快指针找到的非零数赋值给慢指针的位置后将慢指针后移一个位置,同时将快指针所在处的数置为0。循环下去即可。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
slow = fast = 0
while fast < len(nums):
if nums[fast] != 0:
if slow != fast:
nums[slow] = nums[fast]
nums[fast] = 0
slow += 1
fast += 1