Leetcode 283, Move Zeros
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.
inplace的改变一个list,首先要想到的就是可能用two pointers。每次遇到一个非零的nums[j], nums[i]和nums[j]交换,然后 i 指针右移一步
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return [] n = len(nums) ind = 0 for i in range(n): if nums[i] != 0: nums[i], nums[ind] = nums[ind], nums[i] ind += 1

浙公网安备 33010602011771号