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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值