题目:
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.
思路:可以该数组从后向前遍历,遇到0就把0放至末尾;或者从前遍历遇到非0元素则依次放在数组前,最后将后边元素全部置为0
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCode { class MoveZerosSolution { public void MoveZeroes(int[] nums) { //O(n2) for (int i = nums.Length - 1; i >= 0; i--) { if (nums[i] == 0) { for (int j = i; j < nums.Length - 1; j++) { nums[j] = nums[j + 1]; } nums[nums.Length - 1] = 0; } } /*O(1)解法 int index = 0; for(int i = 0;i < nums.Length;i++) if(nums[i] != 0) { nums[index] = nums[i]; index++; } for(int j = index;j < nums.Length;j++) nums[j] = 0; */ } } }