LeetCode-75-颜色分类
in LeetCode with 0 comment

LeetCode-75-颜色分类

in LeetCode with 0 comment

原题地址:颜色分类

给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

注意: 不能使用代码库中的排序函数来解决这道题。

示例:

输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]

进阶:

直观计算

先计算0、1和2的元素个数,再根据个数重写数组。具体的实现如下:

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
const sortColors1 = function(nums) {
    // 统计0,1,2分别出现次数
    let count = [0, 0, 0];
    for (let i = 0; i < nums.length; i ++) {
        count[nums[i]] ++;
    }
    // 清空nums
    nums.splice(0, nums.length);
    // 按0,1,2出现的次数重写nums
    for (let i = 0; i < count.length; i ++) {
        nums.push(...new Array(count[i]).fill(i));
    }
};

测试:

let start = new Date();
const test = sortColors1;
let nums = [2,0,2,1,1,0];
test(nums);
console.log(nums); // [ 0, 0, 1, 1, 2, 2 ]
console.log(new Date().getTime() - start.getTime()); // 8

时间复杂度: 统计个数需要一次遍历,重写需要遍历,时间复杂度为$O(2N)=O(N)$
空间复杂度: 常数级额外空间,空间复杂度为$O(1)$