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

LeetCode 283 - Move Zeroes (Medium)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 283๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ •๋ ฌ์„ ์ˆ˜ํ–‰ํ•œ ๋’ค์— ๊ฐ™์€ ํ‚ค ๊ฐ’์„ ๊ฐ€์ง€๋Š” ์›์†Œ๋“ค์˜ ์ˆœ์„œ๊ฐ€ ๋’ค๋ฐ”๋€Œ์ง€ ์•Š๋Š” ๊ฒƒ์„ stable sort ๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

์ด๋ฒˆ ๋ฌธ์ œ์—์„œ๋Š” ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ 0์„ ๋ฐฐ์—ด์˜ ๋์ชฝ์œผ๋กœ ์˜ฎ๊ฒจ์ฃผ๋˜ ๊ทธ ์ˆœ์„œ๊ฐ€ ๋’ค๋ฐ”๋€Œ๋ฉด ์•ˆ๋˜๋Š” ๋กœ์ง์„ ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.
์ด๋•Œ ๋ณ„๋„์˜ array ๋ฅผ ๋ณต์‚ฌํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๋ฉด ์•ˆ๋˜๊ณ  ๋ฐฐ์—ด ๋‚ด์—์„œ ์ •๋ ฌ์ด in-place ๋กœ ์ˆ˜ํ–‰๋˜์–ด์•ผํ•˜๋ฏ€๋กœ ์‚ฝ์ž…์ •๋ ฌ์„ ํ™œ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

์‚ฝ์ž… ์ •๋ ฌ ์€ ๋ฐฐ์—ด์˜ ๋ ์›์†Œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ์ž์‹ ์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„ ์‚ฝ์ž… ํ•ด์ฃผ๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋Š”๋ฐ,
์—ฌ๊ธฐ์„œ๋Š” 0์„ ๋ฐœ๊ฒฌํ•  ๋•Œ๋งˆ๋‹ค 0์ด ์œ„์น˜ํ•  ์ˆ˜ ์žˆ๋Š” ์œ„์น˜๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ ์ฐพ์Œ์œผ๋กœ์„œ O(N^2) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function (nums) {
  for (let i = nums.length - 1; i >= 0; i--) {
    if (nums[i] === 0) {
      let j = i + 1;
      while (j < nums.length && nums[j] !== 0) {
        nums[j - 1] = nums[j];
        j += 1;
      }
      nums[j - 1] = 0;
    }
  }
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 221 - Maximal Square (Medium)  (0) 2021.03.02
LeetCode 543 - Diameter of Binary Tree (Easy)  (1) 2021.03.02
LeetCode 678 - Valid Parenthesis String (Medium)  (0) 2021.03.02
LeetCode 1094 - Car Pooling (Medium)  (0) 2021.03.02
LeetCode 49 - Group Anagrams (Medium)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€