LeetCode 75 Sort Colors

Posted 月牙儿June

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 75 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.

首先能够想到的思路: 因为只有0,1,2三种值的可能,因此可以利用计数排序(counting sort),设置一个数组存每个值的个数。 两趟遍历:一趟计数,一趟给数组赋新值。

java代码参考:

public class Solution 
    public void sortColors(int[] nums) 
        int[] count=new int[3];
        for(int i:nums)
            count[i]++;
        
        int i=0;
        while(i<nums.length)
            for(int j=0;j<3;j++)
               while(count[j]>0)
                    nums[i]=j;
                    i++;
                    count[j]--;
                 
            
        
        return;
    

进阶思路:

能不能只通过One-Pass实现呢?答案是肯定的。

i表示一趟遍历;j表示第一位不为0的最左边的位置;k表示从右往左第一位不是2的位置。则最终j到k就是1的位置范围。

java实现如下:

public class Solution 
    public static void sortColors(int[] nums) 
        int j=0,k=nums.length-1;
        int i=0;
        while(i<=k)
            if(nums[i]==0)
               swap(nums,i,j);
               j++;i++;
             
            else if(nums[i]==2) swap(nums,i,k--);
            else i++;
        
    
    public static void swap(int[] nums,int a,int b)
        int temp=nums[a];
        nums[a]=nums[b];
        nums[b]=temp;
    


以上是关于LeetCode 75 Sort Colors的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-75-Sort Colors]

Leetcode 75. Sort Colors

LeetCode 75 Sort Colors

LeetCode 75 Sort Colors

leetcode75 Sort Colors

LeetCode75 Sort Colors