zoukankan      html  css  js  c++  java
  • LeetCode 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?

    题目要求是,时间复杂度O(n) 空间复杂度O(1) 对于没有听过三路快排的窝来说,这个medium比hard难得多好趴。。。

     
    先说原理,
     
    快速排序就是找一个基准v,通过双向指针,把<v的值放在左边,>=v的值放在右边,然后递归。
     
    三路,就是 <v, =v, >v。那么如何分成三分呢?
     
    设有一个数组 [0...n] 遍历数组,index 表示遍历到的位置。
     
    找两个分界位置,lt 和 rt 用来表示 =v 和 >v 的最小位置。
     
    如果遇到小于 v 的就让其和lt交换,同时将 lt++。等于 v 不需要做操作。大于 v 就将 lt-- 其和 lt 作交换
     
    之后将 <v 和 >v 的两段递归排序就可以啦。
     
     
    那么这题,只是三路排序的一个思路~~
     
    /*
     * @lc app=leetcode id=75 lang=javascript
     *
     * [75] Sort Colors
     */
    /**
     * @param {number[]} nums
     * @return {void} Do not return anything, modify nums in-place instead.
     */
    var sortColors = function(nums) {
        let n = nums.length;
        let lt = 0, // =v 的第一个
            rt = n; // >v 的第一个
    
        let index = 0;
        let v = 1;
    
        while (index < n && index < rt) {
            if (nums[index] > v) {
                rt--;
                swap(index, rt);
            } else if (nums[index] === v) {
                index++;
            } else if (nums[index] < v) {
                swap(lt, index);
                lt++;
                index++;
            }
        }
    
        function swap(i, j) {
            let t = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
    };
  • 相关阅读:
    Linux 普通用户su命令切换控制
    Linux上的文件管理类命令(2)
    系统内存管理
    ssh 安全配置
    redhat系统安装部署
    Unity截屏
    Unity场景道具模型拓展自定义编辑器
    Unity优化之减少Drawcall
    Unity安卓连接profile调试
    Unity游戏数据用Json保存
  • 原文地址:https://www.cnblogs.com/wenruo/p/10885967.html
Copyright © 2011-2022 走看看