public class Solution { public void MoveZeroes(int[] nums) { int index = 0; for (int i = 0; i < nums.Length; i++) { //[0, 1, 0, 3, 12] //[1, 3, 12, 0, 0] if (nums[i] != 0) { nums[index] = nums[i]; index++; } } for (int i = index; i < nums.Length; i++) { nums[i] = 0; } } }
https://leetcode.com/problems/move-zeroes/#/description
补充一个python的实现:
1 class Solution: 2 def moveZeroes(self, nums: 'List[int]') -> None: 3 """ 4 Do not return anything, modify nums in-place instead. 5 """ 6 i,j = 0,0 7 n = len(nums) 8 while i < n: 9 cur = nums[i] 10 if cur == 0: 11 i += 1 12 else: 13 nums[j] = cur 14 i += 1 15 j += 1 16 while j < n: 17 nums[j] = 0 18 j += 1