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:
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
我的朴素的模拟思想:time,o(n),space,o(1)
//想清楚思路:题目说了,必须原地处理,不能申请额外数组 //那么遍历数组一旦遇到0,就查找他后面第一个不是0的数,将其交换过来 class Solution { public: void moveZeroes(vector<int>& nums) { for(int i=0;i<nums.size();i++) { if(nums[i] == 0) { //找到第一个非0位置 int pos=i+1; while(pos<= nums.size()-1 && nums[pos]==0) pos++; //pos沿途都是0,包括最后一个元素 if(pos >= nums.size() -1 && nums[nums.size()-1]==0 ) break; //交换 nums[i]=nums[pos]; nums[pos]=0; } } } };
学习和参考一下别人家的解法1:(好简单直白的方式,速度稍微慢一点)
//将所有的非0数向前尽可能的压缩,最后把没压缩的那部分全置0就行了。比如103040,先压缩成134,剩余的3为全置为0 class Solution { public: void moveZeroes(vector<int>& nums) { int pos = 0; for (int i = 0; i < nums.size(); ++i){ if (nums[i] != 0) { nums[pos] = nums[i]; pos++; //利用pos记录压缩到的位置 } } //将后面的数全置为0 for (int j = pos; j < nums.size(); j++){ nums[j] = 0; } } };
学习和参考一下别人家的解法2:(给跪了)
可以参考快速排序的partition函数,根据是否为0来划分前后两部分。非0部分是从左往右扩展的可以发现相对顺序不变,0部分相对顺序虽然会变,但所有0都一样所以看不出差异的。
class Solution { public: void moveZeroes(vector<int>& nums) { int i=-1; for(int j=0;j<nums.size();++j) { if(nums[j]!=0) swap(nums[++i],nums[j]); } } };
参考资源:
【1】 网友,_bubble,原文地址,http://blog.csdn.net/rockzh1993/article/details/48971355
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50384568
原作者博客:http://blog.csdn.net/ebowtang