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

linspiration
161 声望53 粉丝

引用和评论

0 条评论