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:
题目要求是,时间复杂度O(n) 空间复杂度O(1) 对于没有听过三路快排的窝来说,这个medium比hard难得多好趴。。。
/* * @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; } };
LeetCode 75. Sort Colors (颜色分类):三路快排
原文:https://www.cnblogs.com/wenruo/p/10885967.html