Move Zeroes
题目链接: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.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [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,则放置在数组最后,但是其他元素的顺序不发生改变;如果不存在0,则保持数组不变。
直观的算法就是设置索引,将所有非0的项全部移动到正确的位置;剩下的全赋值为0。
代码如下:耗时20ms。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int index = 0;
for(int i = 0;i<nums.size();i++)
{
if(nums[i])
{
if(index == i)
index++;
else
nums[index++] = nums[i];
}
}
for(int i = index;i <nums.size();i++)
{
nums[i] = 0;
}
}
};