题目
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].
算法
stl
O(N)
class Solution {
public:
void moveZeroes(vector<int>& nums) {
return fill(remove(nums.begin(),nums.end(),0),nums.end(),0);
}
};
算法
两个指针
O(n)
class Solution {
public:
void moveZeroes(vector<int>& nums) {
if (nums.empty()) return;
int fill=0,cur=0;
int sz=nums.size();
while(cur<sz){
if(nums[cur]!=0)
nums[fill++]=nums[cur];
++cur;
}
while(fill<sz)
nums[fill++]=0;
return;
}
};