Sort Colors Leetcode

Given an array with n objects colored redwhite 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 01, 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).

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?

 

本题类似于快速排序的思路,因为要one-pass,利用两个指针指出1开始的位置和2开始的位置。

从左到右扫描,到right的地方为止,因为2每次换过去都是最终的位置。如果是0,就需要和left交换,交换后0变多一个,此时left要++,如果是1,只要curr++就可以了。

需要注意的是while里面是有等号的,因为没有等号的话最后一次会漏判断。

 

代码如下:

 

class Solution {
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */
    public void sortColors(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        int i = 0;
        while (i <= right) {
            if (nums[i] == 0) {
                swap(nums, i, left);
                i++;
                left++;
                continue;
            }
            if (nums[i] == 1) {
                i++;
                continue;
            }
            if (nums[i] == 2) {
                swap(nums, i, right);
                right--;
            }
        }
    }
    public void swap(int[] a, int b, int c) {
        int tmp = a[b];
        a[b] = a[c];
        a[c] = tmp;
    }
}

 

其实if可以用else if 代替,就不用continue了。。。

 

时隔一个多月又做了一遍。。。居然还没有超级顺利地写出来我也是很难过的。。。需要注意的是当2与右边换的时候需要把i--因为换过来的可能是0.

public class Solution {
    public void sortColors(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int pointerOne = 0;
        int pointerTwo = nums.length - 1;
        for (int i = 0; i <= pointerTwo; i++) {
            if (nums[i] == 0) {
                swap(nums, i, pointerOne);
                pointerOne++;
            }
            if (nums[i] == 2) {
                swap(nums, i, pointerTwo);
                pointerTwo--;
                i--;
            }
        }
    }
    public void swap(int[] nums, int a, int b) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}

 

posted @ 2017-01-08 13:18  璨璨要好好学习  阅读(151)  评论(0编辑  收藏  举报