๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 75 - Sort Colors (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 75๋ฒˆ

ํ’€์ด ๊ณผ์ •

0, 1, 2 ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋Š” ๋ฐฐ์—ด์„ O(n) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„์™€ O(1) ์˜ ๊ณต๊ฐ„ ๋ณต์žก๋„๋ฅผ ํ†ตํ•ด ์ •๋ ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ฒ˜์Œ์— ์–ด๋–ป๊ฒŒ ์ ‘๊ทผํ•ด์•ผํ• ์ง€ ๊ฐ์„ ๋ชป์žก์•„์„œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด์— ํžŒํŠธ๋ฅผ ์–ป์–ด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.
๊ฐ€์žฅ ์ค‘์š”ํ•œ ๊ฒƒ์€ 0 ์„ ์™ผ์ชฝ์— 2 ๋ฅผ ์˜ค๋ฅธ์ชฝ์— ๋ฐฐ์น˜์‹œ์ผœ์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ 1 ์€ ๋ฌด์‹œํ•˜๊ณ  0 ๊ณผ 2 ๋ฅผ ๋งŒ๋‚˜๋ฉด ๋“ค์–ด๊ฐˆ ๋‹ค์Œ ์œ„์น˜๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ํ†ตํ•ด
์œ„์น˜๋ฅผ ๋ณ€๊ฒฝํ•ด์ฃผ๋ฉด O(n) ์— ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด๋•Œ ์ฃผ์˜ํ•  ์ ์€ 2 ๋ฅผ ๋ฐ”๊ฟ€๋•Œ์ธ๋ฐ 2๋ฅผ swap ํ•  ๊ฒฝ์šฐ 0, 1, 2 ์ค‘ ํ•˜๋‚˜์˜ ์ˆซ์ž๊ฐ€ ๋ฐ”๋€ ์œ„์น˜๋กœ ์˜ค๊ฒŒ ๋˜๋Š”๋ฐ,
์—ฌ๊ธฐ์„œ walker ๋ฅผ ๊ทธ๋Œ€๋กœ ์ฆ๊ธฐ์‹œ์ผœ๋ฒ„๋ฆฌ๋ฉด ๊ฒฝ์šฐ์— ๋”ฐ๋ผ์„œ ์ •๋ ฌ์ด ๋‹ค ๋๋‚˜์ง€ ์•Š๊ณ  ๋‹ค์Œ ์œ„์น˜๋กœ ์˜ฎ๊ฒจ์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

์ด ์ ์— ์œ ์˜ํ•˜์—ฌ 2 ๋ฅผ swap ํ•  ๊ฒฝ์šฐ์—๋Š” walker ๋ฅผ ๋ฐ”๋กœ ์ฆ๊ฐ€์‹œ์ผœ ์ฃผ์ง€ ์•Š๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function (nums) {
  let left = 0,
    right = nums.length - 1;
  walker = 0;

  while (walker <= right) {
    if (nums[walker] === 2 && walker < right) {
      [nums[walker], nums[right]] = [nums[right], nums[walker]];
      right--;
    } else if (nums[walker] === 0) {
      [nums[walker], nums[left]] = [nums[left], nums[walker]];
      left++;
      walker++;
    } else {
      walker++;
    }
  }

  return nums;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€