Leetcode 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.

click to show follow up.

Follow up:
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 简而言之,遇到0,交换到前面,遇到2, 交换到后面。用双指针left, right来记录当前已经就位的0序列和2序列的边界位置。
假设已经完成到如下所示的状态:
 
0......0   1......1  x1 x2 .... xm   2.....2
              |           |               |
            left        cur          right
 
(1) A[cur] = 1:已经就位,cur++即可
(2) A[cur] = 0:交换A[cur]和A[left]。由于A[left]=1或left=cur,所以交换以后A[cur]已经就位,cur++,left++
(3) A[cur] = 2:交换A[cur]和A[right],right--。由于xm的值未知,cur不能增加,继续判断xm。
     cur > right扫描结束。

Java code:
public class Solution {
    public void sortColors(int[] nums) {
        if(nums == null || nums.length < 2) {
            return;
        }
        int left = 0, right = nums.length-1;
        int i = 0;
        while( i <= right) {
            if(nums[i] == 0) {
                swap(nums, i, left);
                i++;
                left++;
            }else if(nums[i] == 1) {
                i++;
            }else if(nums[i] == 2) {
                swap(nums, i, right);
                right--;
            }
        }
    }
    
    private void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-sort-colors.html

 

posted @ 2015-10-11 11:06  茜茜的技术空间  阅读(131)  评论(0编辑  收藏  举报