Leetcode :: Missing Number

์ˆ‘์ˆ‘ยท2021๋…„ 6์›” 6์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
105/122
post-thumbnail

Problem

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?


Guess

  • ๋น ์ง„ ์ˆ˜๋ฅผ ์ฐพ๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค๋ผ.. ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•˜๋ฉด ์ˆœ์‹๊ฐ„์— ํ’€๊ฒ ์ง€๋งŒ
  • Follow up ํ•ญ๋ชฉ์„ ๋”ฐ๋ผ๊ฐ€๋ ค๋ฉด ์กฐ๊ธˆ ๋ฐœ์ƒ์˜ ์ „ํ™˜์ด ํ•„์š”ํ•˜๋‹ค. (๋”•์…”๋„ˆ๋ฆฌ๋Š” ๊ณต๊ฐ„๋ณต์žก๋„ O(n))
  • ์ƒ์ˆ˜ ๊ณต๊ฐ„์œผ๋กœ ํ•ด๊ฒฐํ•  ๋ฐฉ๋ฒ•์ด ๋„์ €ํžˆ ๋– ์˜ค๋ฅด์ง€ ์•Š์•˜๋Š”๋ฐ, XOR์„ ์ด์šฉํ•œ ์œ ๋‹ˆํฌํ•œ ์†”๋ฃจ์…˜์„ ๋ฐœ๊ฒฌํ–ˆ๋‹ค.

1 ^ 1 = 0
0 ^ 0 = 0
0 ^ 1 = 1

XOR์€ ์ด์ฒ˜๋Ÿผ ์„œ๋กœ ๊ฐ™์œผ๋ฉด 0, ๋‹ค๋ฅด๋ฉด 1์„ ๋ถ€์—ฌํ•˜๋Š” ๋น„ํŠธ์—ฐ์‚ฐ์ด๋‹ค.
์ค‘์š”ํ•œ ํŠน์„ฑ์€, 0๊ณผ a๊ฐ€ XORํ•˜๋ฉด ๋ฌด์กฐ๊ฑด a๊ฐ€ ๋‚˜์˜ค๊ฒŒ ๋˜์–ด์žˆ๋‹ค.

์ฆ‰, ๋ฒ”์œ„ [0...n] ์˜ ๋ชจ๋“  ์š”์†Œ์™€ XOR์„ ํ•˜๋ฉด, ์„œ๋กœ ๋‹ค๋ฅธ ์ˆ˜ ์ผ ๋•Œ ๋ฌด์กฐ๊ฑด 0์ด ์•„๋‹Œ ์ˆ˜๊ฐ€ ๋‚˜์˜จ๋‹ค! -> ์‚ฌ๋ผ์ง„ ์ˆ˜๊ฐ€ ๋œ๋‹ค.

Solution

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        missing = len(nums)
        for i,num in enumerate(nums):
            missing ^= i ^ num
        return missing
profile
ํˆด ๋งŒ๋“ค๊ธฐ ์ข‹์•„ํ•˜๋Š” ์‚ฝ์งˆ ์ „๋ฌธ(...) ์ฃผ๋‹ˆ์–ด ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€