LeetCode 75 Sort Colors 颜色分类
描述
Given an array nums 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.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sort-colors
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
/**
* 用一个数组typeArr记录元素频次, 索引为元素值,值为频次
* 遍历typeArr, 根据位置和频次填充原数组
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var sortColors = function (nums) {
const typeArr = []
for (let i = 0; i < nums.length; i++) {
typeArr[nums[i]] = (typeArr[nums[i]] || 0) + 1
}
let cur = 0
for (let i = 0; i < typeArr.length; i++) {
const count = typeArr[i] || 0
nums.fill(i, cur, cur + count)
cur += typeArr[i] || 0
}
};

浙公网安备 33010602011771号