题目描述:
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]
中文理解:给定一个数组,将0移动到数组末尾,其他数字保持原来的相对位置关系。
解题思路:使用zeros变量计数0的个数,将nums[i-zeros]=nums[i],最后将后面的数组部分补0。
代码(java):
class Solution {
public void moveZeroes(int[] nums) {
int zeros=0;
int index=0;
for(int val:nums){
if(val==0)zeros++;
else{
nums[index-zeros]=nums[index];
}
index++;
}
for(int i=nums.length-zeros;i<nums.length;i++){
nums[i]=0;
}
}
}