zoukankan      html  css  js  c++  java
  • leetCode(30):Sort Colors

    Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

    Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.




    void sortColors(vector<int>& nums)
    {//排序时间复杂度O(n)
    	int length=nums.size();
    	int zero=0;
    	int two=length-1;
    	while(zero<length && nums[zero]==0)
    	{//找到第一个不为0的数的下标
    		zero++;
    	}
    	while(two>=zero && nums[two]==2)
    	{//找到倒数第一个不为2的数的下标,zero前的数都是0
    		two--;
    	}
    
        for(int i=zero;i<=two;++i)
        {
        	if(nums[i]==0)
        	{//假设为0,和zero指向的数交换,zero前移
        		nums[i]=1;//zero指向的值肯定是1,首先不可能为0,其次,i遍历过的地方,2都已经换到最后
        		nums[zero]=0;
        		zero++;
        	}
        	else if(nums[i]==1)
        	{//假设为1,则跳过
        		continue;
        	}
        	else
        	{//假设为2。则和two指向的数交换,并更新two的值。
        		//和zero不同,two前面的数可能还未排序
        		nums[i]=nums[two];
        		nums[two]=2;
        		two--;
        		while(two>=i && nums[two]==2)
        		{
        			two--;
        		}
        		i--;//先向后退一步。由于two指向的数还未进行排序
        	}
        }
    }


  • 相关阅读:
    SSM商城项目(二)
    SSM商城项目(一)
    Solr
    Lucene
    TP5分页函数paginate中的each()传参
    微信小程序+php 授权登陆,完整代码
    thinkphp5 + barcode 生成条形码
    微信小程序-获取当前位置和城市名
    PHP查询附近的人及其距离的实现方法
    thinkphp5连接sql server
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7079863.html
Copyright © 2011-2022 走看看