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;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章