268. Missing Number

2021. 10. 27. 03:23Leetcode

Description:

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.

 

'''
[1] two pass)

idea::
[0,n] -> exclusive XOR -> ans
ans-> for num in nums: ans^=num -> ans

-T/C: O(n+1 + n) =O(2n) =O(n)
-S/C: O(1)
'''
'''
[2] one pass)

idea::
while XOR operation in nums, also do XOR opeartion j.
after loop, ans^=j. then return ans

code::
(below)

-S/C: O(n+1)=O(n)
-T/C: O(1)
'''
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        j=0;
        ans=0;
        for num in nums:
            ans=ans^num^j
            j+=1
        ans^=j
        return ans

'Leetcode' 카테고리의 다른 글

234. Palindrome Linked List  (0) 2021.10.27
9. Palindrome Number  (0) 2021.10.27
338. Counting Bits  (0) 2021.10.27
278. First Bad Version  (0) 2021.10.26
226. Invert Binary Tree  (0) 2021.10.26