[LintCode/LeetCode] Sort Colors I & II

本文介绍了一种高效的颜色排序算法,该算法能在一次遍历内完成排序,并且只使用常数空间。通过双指针技巧实现0、1、2的排序,并扩展至k种颜色的情况。

Sort Color I

Problem

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.

Notice

You are not suppose to use the library's sort function for this problem.
You should do it in-place (sort numbers in the original array).

Example

Given [1, 0, 1, 2], sort it in-place to [0, 1, 1, 2].

Challenge

A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

Note

第一题可以使用双指针法,构造swap函数,将0换到左边,将2换到右边,遇到1跳过。
另一种方法如下所示,构造色彩数组。然后对nums重新分配数值。

Solution

Update 2018-9

class Solution {
    public void sortColors(int[] nums) {
        if (nums == null || nums.length < 2) return;
        int m = 0, n = nums.length-1; //m is index of 0's, n is index of 2's
        for (int i = 0; i <= n; i++) {
            if (nums[i] == 0) swap(nums, i, m++);
            else if (nums[i] == 2) swap(nums, i--, n--);
        }
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

2016 version

class Solution {
    public void sortColors(int[] nums) {
        int[] count = new int[3];
        for (int num: nums) {
            count[num]++;
        }
        int pos = 0;
        for (int i = 0; i < 3; i++) {
            while (count[i] > 0) {
                nums[pos++] = i;
                count[i]--;
            }
        }
        return ;
    }
}

Sort Colors II

Problem

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

Notice

You are not suppose to use the library's sort function for this problem.

Example

Given colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].

Note

Sort Color I的做法一样。

Solution

class Solution {
    public void sortColors2(int[] colors, int k) {
        int[] count = new int[k + 1];
        for (int i : colors) {
            count[i]++;
        }
        int pos = 0;
        for (int i = 1; i <= k; i++) {
            while (count[i] > 0) {
                colors[pos++] = i;
                count[i]--;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值