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--; //后面往前调的数值不能跳过,要再判断一次
                }
            }
        }
    }
  • 相关阅读:
    EasyUI限制时间选择(开始时间小于结束时间)
    C# readonly与const的区别
    C# Lambda 表达式
    C# 扩展方法
    C# 枚举enum
    Visual Studio中的“build”、“rebuild”、“clean”的区别
    无root开热点教程
    数据库锁
    安卓:标题栏右上角添加按钮
    安卓:从assets目录下复制文件到指定目录
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5383434.html
Copyright © 2011-2022 走看看