zoukankan      html  css  js  c++  java
  • Leetcode 75 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.

    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?

    public class S075 {
        public void sortColors(int[] nums) {
            //首先想到的方法,但是额外空间复杂度不是常数
    /*        int num0[] = new int[nums.length];
            int num1[] = new int[nums.length];
            int num2[] = new int[nums.length];
            int count0 = 0,count1 = 0,count2 = 0;
            for (int i = 0;i<nums.length;i++) {
                if (nums[i] == 0){
                    count0++;
                } else if (nums[i] == 1){
                    num1[count1] = 1;
                    count1++;
                } else {
                    num2[count2] = 2;
                    count2++;
                }
            }
            System.arraycopy(num0, 0, nums, 0, count0);
            System.arraycopy(num1, 0, nums, count0, count1);
            System.arraycopy(num2, 0, nums, count0+count1, count2);*/
            //只扫描一遍而且空间复杂度为常数的算法
            //遇到0往前调,遇到2往后调,调的位置根据0或2的当前个数来决定
            int num0 = 0,num2 = 0;
            for (int i = 0;i<nums.length-num2;i++) {
                if (nums[i] == 0) {
                    nums[i] = nums[num0];
                    nums[num0] = 0; 
                    num0++;
                } else if (nums[i] == 2){
                    nums[i] = nums[nums.length-num2-1];
                    nums[nums.length-num2-1] = 2;
                    num2++;
                    i--; //后面往前调的数值不能跳过,要再判断一次
                }
            }
        }
    }
  • 相关阅读:
    模板的一些概念和技巧
    [转] Linux TCP/IP网络小课堂:net-tools与iproute2大比较
    [转] boost库的Singleton的实现以及static成员的初始化问题
    static对象的高级用法
    const中的一些tricky的地方
    delphi软件启动的顺序解密。
    属性名、变量名与 内部关键字 重名 加&
    delphi Inc函数和Dec函数的用法
    Centos 关闭防火墙
    IntelliJ IDEA 启动方法
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5383434.html
Copyright © 2011-2022 走看看