LeetCode 75 Sort Colors

来源:互联网 发布:c语言true和false 编辑:程序博客网 时间:2024/05/03 01:53

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;    }}


0 0