您的位置:首页 > 其它

<LeetCode OJ> Move Zeroes【283】

2015-12-23 09:45 537 查看


283. Move Zeroes

My Submissions

Question

Total Accepted: 40008 Total
Submissions: 94323 Difficulty: Easy

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:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
Array Two
Pointers

Show Similar Problems

朴素的模拟思想:O(N)

//想清楚思路:题目说了,必须原地处理,不能申请额外数组
//那么遍历数组一旦遇到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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: