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.javascript
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.java
Note: You are not suppose to use the library's sort function for this problem.數組
Example:app
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
Follow up:this
題目要求是,時間複雜度O(n) 空間複雜度O(1) 對於沒有聽過三路快排的窩來講,這個medium比hard可貴多好趴。。。spa
/* * @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; } };