https://leetcode.com/problems/move-zeroes/description/
Solution 1, use iterators to erase 0s and add 0 to the end.
void moveZeroes(vector<int>& nums) {
vector<int>::iterator it=nums.begin();
for(int i=0;i<nums.size();i++) {
if(*it == 0) {
nums.erase(it);
nums.push_back(0);
}
else
it++;
}
}
Solution 2, for i = 0 to nums.size()-1, copy nums[i] to an array starts from j=0. Since non-zeros is less than nums.size() and i>=j always, just use &nums[0] for the copied array.
void moveZeroes(vector<int>& nums) {
int j = 0;
for(int i=0;i<nums.size();i++) {
if(nums[i]!=0) {
nums[j++] = nums[i];
}
}
while(j<nums.size()) {
nums[j] = 0; ->
j++;
}
}
No comments:
Post a Comment