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.
题意:移除给定数组中的0元素,将0元素移动到数组的末尾,并且保持不是0元素的元素的顺序。
思路: 可以利用一个指针将不是0 的元素尽可能的往前排,然后将剩余的全部设置为0。
代码:
public void moveZeroes(int[] nums) { int cnt =0,pos = 0; int len = nums.length; for(int i =0;i<len;i++){ //非0元素向前移 if(nums[i]!=0){ nums[pos] = nums[i]; pos++; } } //其余元素设置为0 for(;pos<len;pos++){ nums[pos]= 0; } }