码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 75] Sort Colors

时间:2015-07-14 20:17:48      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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.

Note:
You are not suppose to use the library‘s sort function for this problem.

public class Solution {
    public void sortColors(int[] nums) {
        /*左边的指针red跟踪red,右边的指针blue跟踪blue
        用i指针从左边向右边扫描,如果碰到red就换到左边,如果碰到blue就换到右边
        如果即不是red也不是blue,i就往后移动
        时间复杂度O(n)*/
        //解法二:利用计数器方法,因为一共就3种颜色,因此数组长度设为3即可,遍历nums,记录每个颜色出现的次数,再重现数组
      /*  int i=0;
        int red=-1;
        int blue=nums.length;
        while(i<blue){//i的范围,遍历到blue即可
            if(nums[i]==0){
                swap(nums,i++,++red);
            }else{
                if(nums[i]==2){
                    swap(nums,i,--blue);
                }else{
                    i++;
                }
            }
        }
        
    }
    public void swap(int nums[],int i,int j){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }*/
    int flag[]=new int[3];
    for(int i=0;i<nums.length;i++){
        flag[nums[i]]++;
    }
    int index=0;
    for(int i=0;i<3;i++){
        int temp=flag[i];
        for(int j=0;j<temp;j++){
            nums[index++]=i;
        }
    }
    }
    
    
}

 

[leedcode 75] Sort Colors

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4646177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!