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. Sort Colors #208

Open
Tcdian opened this issue Jun 11, 2020 · 1 comment
Open

75. Sort Colors #208

Tcdian opened this issue Jun 11, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 11, 2020

75. Sort Colors

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

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

Example

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Note

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

Follow up

  • 一个直观的解决方案是使用计数排序的两趟扫描算法。
    首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 11, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
    let red = 0;
    let blue = nums.length - 1;
    let i = 0;
    while (i <= blue) {
        if (nums[i] === 0) {
            swap(nums, i++, red++);
        } else if (nums[i] === 2) {
            swap(nums, i, blue--);
        } else {
            i++;
        }
    }
};

function swap(nums, x, y) {
    let temp = nums[x];
    nums[x] = nums[y];
    nums[y] = temp;
}
  • TypeScript Solution
/**
 Do not return anything, modify nums in-place instead.
 */
function sortColors(nums: number[]): void {
    let red = 0;
    let blue = nums.length - 1;
    let i = 0;
    while (i <= blue) {
        if (nums[i] === 0) {
            swap(nums, i++, red++);
        } else if (nums[i] === 2) {
            swap(nums, i, blue--);
        } else {
            i++;
        }
    }
}

function swap(nums: number[], x: number, y: number) {
    let temp = nums[x];
    nums[x] = nums[y];
    nums[y] = temp;
}

@Tcdian Tcdian added the Classic label Jun 11, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant