283. Move Zeroes
问题描述:
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.
解题思路:
我们可以用两个变量来一起遍历。
新数组下标idx, 和原数组i
当nums[i] != 0的时候,令nums[idx] = nums[i]并且idx++
最后要把idx以及剩余位置填上0.
代码:
class Solution { public: void moveZeroes(vector<int>& nums) { int idx = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] != 0){ nums[idx++] = nums[i]; } } for(int i = idx; i < nums.size(); i++){ nums[i] = 0; } } };