Level:
Easy
题目描述:
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.
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.
思路分析:
根据题目要求,不能使用额外的空间,并且当移动零后其他元素的相对位置不变,我们可以在遍历数组的过程中,将不为0的元素,重新填充在原数组中,以index=0为下标开始,遇到一个不为0的元素,index加1。遍历完整个数组,然后从index开始,将index到数组尾部的所有元素都置为0,就得到了最终的结果。
代码:
class Solution {
public void moveZeroes(int[] nums) {
int index=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=0)
nums[index++]=nums[i];
}
for(int j=index;j<nums.length;j++){
nums[j]=0;
}
}
}