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:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
//思路:从左往右,遇到0,则0后面的所有元素往前移动一位,有多少0,移动多少回,最后末尾添加0
void moveZeroes(vector<int>& nums) {
int count=0;
for(int i=0;i<nums.size();i++)
if(nums[i]==0)
count++;
int tmp=count;
for(int i=0; tmp>0 && i<nums.size(); i++){
if(nums[i]==0){
for(int j=i;j<nums.size()-1;j++)
nums[j]=nums[j+1];
tmp--;
i--; // in case that start with 00
}
}
for(int i=0;i<count;i++)
nums[nums.size()-1-i]=0;
}
//别人的做法:
void moveZeroes(vector<int>& nums) {
int j = 0;
// move all the nonzero elements advance
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
for (;j < nums.size(); j++) {
nums[j] = 0;
}
}
刷leetcode的最爽的地方不在于一次次的Accepted,而是自己的绞尽脑汁,想出来自认为还不错的代码,AC后看到讨论区里,大神们更优雅更精致的代码后,被虐的那个酸爽。大呼,哎呦卧槽,我怎么没想到。。。