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--; //后面往前调的数值不能跳过,要再判断一次
                }
            }
        }
    }
  • 相关阅读:
    vue : 无法加载文件 C:Users1AppDataRoaming pmvue.ps1,因为在此系统上禁止运行脚本
    Flutter 常用的第三方库
    Dart 中的类
    Flutter 学习
    在 VSCode 中开发Flutter项目
    Flutter 环境配置的一些坑
    前端资源和优秀项目地址
    一小时学习JQuery材料
    基于RCT6的YX6100语音模块方案
    Java中反射和内省代码实例
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5383434.html
Copyright © 2011-2022 走看看