zoukankan      html  css  js  c++  java
  • 283. Move Zeroes

    原文题目:

    283. Move Zeroes

    读题:

    将数组中元素0移到数组的后面,其他元素的相对位置保持不变,那么就不能用快速排序的分治法思想了,用两个指针在头和尾进行遍历

    解题:

    1)取两个索引,一个索引i指向第一个0,另一个索引j在索引i之后寻找第一个不为0的元素,交换位置,直至最后

    2)由于不能copy数组,因此遍历数组,如果遇到0则跳过,非0则放入数组中,然后在尾部补齐0即可;

    AC代码:

    //方法一:交换
    class Solution {
    public:
    	void swap(int *a,int *b)
    	{
    		int temp = *a;
    		*a = *b;
    		*b = temp;
    	}
    	void moveZeroes(vector<int>& nums) 
    	{
    		int len = nums.size();
    		int i =0;
    		int j =0;
    		int temp =0;
    		if (!len)
    			return;
    		while(i < len && j < len)
    		{
    			while(i < len &&nums[i]!=0)
    			{
    				i++;
    			}
    			if(i < len)
    			{
    				j = i+1;
    				while(j < len &&nums[j]==0)
    				{
    					j++;
    				}
    				if(j < len)
    				{
    					swap(&nums[i],&nums[j]);
    				}
    				 
    			}		
    		}
    	}
    };
    //方法二:先添加非0,然后补齐0
    class Solution 
    {
    public:
    	void moveZeroes(vector<int>& nums) 
    	{
    		int size = nums.size();
    		if (!size)
    			return;
    		int i = 0, j = 0;
    		while(i < size)
    		{
    			if (!nums[i])
    			{
    				i++;
    			}
    			else
    			{
    				nums[j++] = nums[i++];
    			}
    		}
    		while(j < i)
    		{
    			nums[j++] = 0;
    		}
    	}
    };
    int main()
    {
    	
    	Solution s;
    	int result;
    	vector <int> vec;
    	vec.push_back(2);
    	//vec.push_back(0);
    	//vec.push_back(0);
    	vec.push_back(1);
    	//vec.push_back(0);
    
    	s.moveZeroes(vec);
    	for(int i =0; i < vec.size();i++)
    	{
    		cout << vec[i] << endl;
    	}
    	getchar();
    }
    

      

  • 相关阅读:
    Mybatis应用
    MyBatis
    jQuery中.bind() .live() .delegate() .on()的区别
    SpringMVC (八)SpringMVC返回值类型
    SpringMVC(七)参数的自动装配和路径变量
    SpringMVC (六)注解式开发
    SpringMVC (五)视图解析器
    SpringMVC (四)MultiActionController
    SourceTree的使用
    Idea中使用git
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8361721.html
Copyright © 2011-2022 走看看