Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

75. 颜色分类 #31

Open
webVueBlog opened this issue Sep 4, 2022 · 0 comments
Open

75. 颜色分类 #31

webVueBlog opened this issue Sep 4, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

75. 颜色分类

Description

Difficulty: 中等

Related Topics: 数组, 双指针, 排序

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

我们使用整数 0、 12 分别表示红色、白色和蓝色。

必须在不使用库的sort函数的情况下解决这个问题。

示例 1:

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

示例 2:

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

提示:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i]012

进阶:

  • 你可以不使用代码库中的排序函数来解决这道题吗?
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @return {void}
 * 
 */
// 遇到0,把0放在数组最前方,此时i位置没变,不用处理
// 遇到2,把2放在数组最后放,此时i向后偏移了1,需要进行i--,然后数组末尾的2已经被统计过了,所以len可以对应再减1,避免重复的问题

var sortColors = function(nums) {
    let len = nums.length
    for (let i = 0; i < len; i++) {
        if (nums[i] === 0) {
            nums.splice(i, 1)
            nums.unshift(0)
        } else if (nums[i] === 2) {
            nums.splice(i, 1)
            nums.push(2)
            len--
            i--
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant