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.

Note:
You are not suppose to use the library’s sort function for this problem.
For example: [1,2,1,1,0,0,2,1,0]

思路

  • 思路1:快速排序的变体,见《算法-第四版》P189
  • 思路2:桶排序
  • 更正一下思路一:这道题其实可能可以不用递归调用的,因为只有三个数,一次运行后,有可能就会对的,但是必须保证切分点是中间值,如原始输入为[1,0,2]可以Accept,[0,1,2]就不能过。所以还是需要递归。

实现

快速排序
class Solution {

    public void exch(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void sortQuickThreeWay(int[] nums, int lo, int hi){
        if (hi <= lo)
            return;
        int less = lo;
        int i = lo + 1;
        int great = hi;
        int v = nums[lo];
        while(i <= great){
            if (nums[i] < v) exch(nums, less++, i++);
            else if (nums[i] > v) exch(nums, i, great--);
            else i++;
        }
        sortQuickThreeWay(nums, lo, less-1);
        sortQuickThreeWay(nums, great+1, hi);
    }

    public void sortColors(int[] nums) {
        sortQuickThreeWay(nums, 0, nums.length-1);
    }
}
桶排序
class Solution {

    public void sortColors(int[] nums) {
        if (nums.length <= 1){
            return;
        }
        int[] states = new int[3];
        for (int i = 0; i < nums.length; i++){
            states[nums[i]]++;
        }
        for (int j = 1; j < 3; j++){
            states[j] += states[j-1];
        }
        Arrays.fill(nums, 0, states[0], 0);
        Arrays.fill(nums, states[0], states[1], 1);
        Arrays.fill(nums, states[1], states[2], 2);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值