zoukankan      html  css  js  c++  java
  • 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++;
                }
            }        
        }
  • 相关阅读:
    状态压缩 + 暴力 HDOJ 4770 Lights Against Dudely
    简单几何(推公式) UVA 11646 Athletics Track
    简单几何(四边形形状) UVA 11800 Determine the Shape
    简单几何(求交点) UVA 11437 Triangle Fun
    计算几何模板
    简单几何(相对运动距离最值) UVA 11796 Dog Distance
    简单几何(求划分区域) LA 3263 That Nice Euler Circuit
    覆盖的面积 HDU
    Desert King 最小比率生成树 (好题)
    约会安排 (区间合并)毒瘤题
  • 原文地址:https://www.cnblogs.com/lyInfo/p/9113666.html
Copyright © 2011-2022 走看看