86dccd30c4424cccaf651f7c42d6becc.png

【题目】:283. 移动零

class Solution {
public:
void moveZeroes(vector<int>& nums) {
for(int l = 0, r = 0; r < nums.size(); ++r) {
if(nums[r] != 0) {
swap(nums[l++], nums[r]);
}
}
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

先把非0的元素移到前边,后边剩下的就是0了。
l:非0元素的末尾
r:0元素的开头