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
    }
};
posted @   IslandZzzz  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示