75. Sort Colors

75. Sort Colors

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

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 a one-pass algorithm using only constant space?

  题目Follow up 既然已经这么大方的给出了解题思路,那就先实现一遍再说。

  基本思想是,使用三个变量,先遍历一次数组,记下0,1,2出现的次数,然后根据第一次遍历的结果,为原数组赋上对应的值,代码如下:

    public void sortColors(int[] nums) {
        int[] countColors = new int[3];
        for(int i : nums){
            switch(i){
            case 0:
                countColors[0]++;
                break;
            case 1:
                countColors[1]++;
                break;
            case 2:
                countColors[2]++;
                break;
            }
        }
        int start = 0;
        while(countColors[0]-- > 0){
            nums[start++] = 0;
        }
        while(countColors[1]-- > 0){
            nums[start++] = 1;
        }
        while(countColors[2]-- > 0){
            nums[start++] = 2;
        }
    }

  空间占用更少的解法,可以设置2个指针,在遍历的同时遇到0,则将当前元素和指向数组头的指针元素交换,同时指针加一,同理遇到2则和数组尾元素交换位置。代码如下:

    public void sortColors(int[] nums) {
        int index = 0, pLeft = 0, pRight = nums.length - 1;
        while(index <= pRight){
            if( 0 == nums[index]){
                nums[index] = nums[pLeft];
                nums[pLeft] = 0;
                pLeft++;
                index++;
            } else if(2 == nums[index]){
                nums[index] = nums[pRight];
                nums[pRight] = 2;
                pRight--;
            } else{
                index++;
            }
        }        
    }
原文地址:https://www.cnblogs.com/lyInfo/p/9113666.html