https://blog.csdn.net/CrazyOnes/article/details/88149530
今天问马哥在学啥,他直接给我一个这个。我研究一下午,最后还是gg。。看了题解恍然大悟,这里简单记录一下,完整版请参考链接。
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.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
我最开始的想法是:
1.找到一共有多少个0,然后集体移动。(思路不对)
2.直接把数组转成int,然后再做。([1,0,12,0,4]这个数组,有12这种数字,只能用str拼接,但是如果数组很大,这个消耗也是O(2n),还是挺大的,不过也算是个想法吧)
标准解法:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int firstZero = 0;
for(int i=0;i<n;++i){
//如果这个值不为0,则交换。当然有的地方是自己换自己,但是不会带来问题。
if(nums[i]!=0){
int tmp = nums[i];
nums[i] = nums[firstZero];
nums[firstZero++] = tmp;//firstZero别忘了++
}
}
}
};
two pointer的思想,这个直接交换(有时候是自己换自己的操作我确实没有想到)这里有点东西。