问题描述
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元素进行操作,因为erase之后会出现空缺,此时指针应该前移一位。
代码
class Solution {
public:
void moveZeroes(vector<int>& nums) {
if (nums.size() == 0)
return;
int j = 0;
for (int i = 0; i < nums.size(); i++){
if (nums[j] == 0){
nums.erase(nums.begin() + j);
nums.push_back(0);
j--;
}
j++;
}
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
反思
一开始没想到去掉一个元素之后就不能继续i++了;然后又对i进行操作结果TLE了,循环无法结束。最后终于可以了~