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.
思路:
1.使用双指针i和k,i用来遍历数组,k用来标记最后一位非零数字,每次nums[i]遇到非零值就赋值给nums[k],最后把剩余的数字赋值零即可。
参考代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n=nums.size(),i=0,k=0;
for(int i=0;i<n;++i){
if(nums[i]!=0){
nums[k++]=nums[i];
}
}
while(k<n) nums[k++]=0;
return ;
}
};