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

LeetCode 287 - Find the Duplicate Number (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 287๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ์ค‘๋ณต๋œ ์›์†Œ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋‹ค๋งŒ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(N^2) ๋ณด๋‹ค ๋‚ฎ์•„์•ผ ํ•˜๋ฉฐ O(1) ์˜ ์ถ”๊ฐ€์ ์ธ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค๋Š” ์ œ์•ฝ ์กฐ๊ฑด์ด ์žˆ์Šต๋‹ˆ๋‹ค.

์ฒ˜์Œ์—๋Š” ๋น„ํŠธ ๋งˆ์Šคํ‚น ์„ ์ด์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€๋ ค๊ณ  ํ–ˆ์ง€๋งŒ Javascript ์—์„œ ๋น„ํŠธ ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ
ํ”ผ์—ฐ์‚ฐ์ž๋ฅผ 32๋น„ํŠธ๋กœ ์ทจ๊ธ‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด๋ฅผ ๋„˜์–ด์„ค ๊ฒฝ์šฐ overflow ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.

์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ์ด๋ถ„ ํƒ์ƒ‰ ์ด ์žˆ์Šต๋‹ˆ๋‹ค.
๋ฐฐ์—ด์—์„œ ์ค‘๋ณต๋œ ์›์†Œ๋Š” ์˜ค์ง ํ•˜๋‚˜์ด๋ฉฐ ๋‚˜๋จธ์ง€ ์›์†Œ๋“ค์€ 1 ~ n ์˜ ์ˆซ์ž๋“ค ์ค‘ ํ•˜๋‚˜์˜ ์ˆซ์ž์™€ ๋งค์นญ๋˜๊ธฐ ๋•Œ๋ฌธ์—
์ด๋ถ„ ํƒ์ƒ‰ ์„ ํ™œ์šฉํ•ด์„œ ์ค‘๋ณต๋œ ์›์†Œ๋ฅผ ์ฐพ์•„์ฃผ๊ธฐ๋กœ ํ–ˆ์Šต๋‹ˆ๋‹ค.

ํŠน์ • ๊ธฐ์ค€ ๊ฐ’ pivot ๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ์ž‘์€ ์›์†Œ์˜ ๊ฐœ์ˆ˜๊ฐ€ pivot ๋ณด๋‹ค ํด ๊ฒฝ์šฐ
pivot ์ดํ•˜์˜ ์ˆซ์ž ์ค‘์—์„œ ์ค‘๋ณต๋œ ์›์†Œ๊ฐ€ ์กด์žฌํ•จ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ lo & hi ๊ฐ’์„ ์„ค์ •ํ•ด์ฃผ๊ณ  ์ด๋ถ„ ํƒ์ƒ‰ ์„ ํ†ตํ•ด ๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ์ขํ˜€๋‚˜๊ฐ€๋ฉด์„œ
๊ฐ๊ฐ์˜ pivot ๋ณด๋‹ค ์ž‘์€ ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค๋ฉด O(NlogN) ์— ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @return {number}
 */
var findDuplicate = function (nums) {
  let lo = 1;
  let hi = nums.length - 1;

  let ans = 0;
  while (lo <= hi) {
    let mid = Math.floor((lo + hi) / 2);

    if (count(nums, mid) > mid) {
      ans = mid;
      hi = mid - 1;
    } else {
      lo = mid + 1;
    }
  }

  return ans;
};

function count(nums, pivot) {
  return nums.filter((e) => e <= pivot).length;
}
๋ฐ˜์‘ํ˜•

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

LeetCode 739 - Daily Temperatures (Medium)  (0) 2021.03.03
LeetCode 114 - Flatten Binary Tree to Linked List (Medium)  (0) 2021.03.03
LeetCode 347 - Top K Frequent Elements (Medium)  (0) 2021.03.03
LeetCode 322 - Coin Change (Medium)  (0) 2021.03.03
LeetCode 46 - Permutations (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€