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的元素放到数组的末尾。本题是一道常规题目,核心思想是记录数组中不为零的元素索引,在遍历数组的过程中维护此索引,直到遍历到数组的结尾,具体如下:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int i = 0;
for(int j = 0; j < nums.size(); j++)
{
if (nums[j] != 0)
nums[i++] = nums[j];
}
for( ; i < nums.size(); i++)
nums[i] = 0;
}
};
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int tmp = 0, j = 0;
for(int i = 0, end = nums.size(); i < end; i++)
{
tmp = nums[i];
if(tmp != 0)
{
nums[i] = nums[j];
nums[j++] = tmp;
}
}
}
};