1. Description
There is an array nums size of n. We have to move all ‘0’ to the end and maintain the relative orders of non-zero elements. Space complexity must be O(1).
2.Algorithm
Two pointers
3.Analysis
O(1) space complexity means we can not use any data structures to assist. To maintain the relative order, every time we move a ‘0’ to the end, we let the element after this ‘0’ move forward by one step. Because the element after ‘0’ move forward, an empty seat appears in the end of the array. We just need to put ‘0’ in these empety seats in the end.
Notice that the type of function is void, so we do not need to return nums.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int ap = 0, zp = 0;
for(int i = 0; i < nums.size();i++){
if(nums[ap] == 0){
ap++;
}
else{
nums[zp] = nums[ap];
zp++;
ap++;
}
}
while(zp < nums.size()){
nums[zp] = 0;
zp++;
}
}
};
4.Complexity
TIme complexity: O(n)
Space complexity: O(1)