- Date : 2021.07.18(일)
- Time : 20분
- 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?
- n == nums.length
- 1 <= n <= 10^4
- 0 <= nums[i] <= n
- All the numbers of nums are unique.
- Input: nums = [3,0,1]
- Output: 2
- Explanation:
n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
def missingNumber(self, nums: List[int]) -> int:
nums.sort()
for i in range(0, nums[-1] + 1, 1):
if i != nums[i]:
return i
return nums[-1]+1
: 0~n의 연속이기 때문에 만약 모든 숫자가 있다면 인덱스와 배열 값이 일치해야한다. 그렇기 때문에 for문이 돌면서 일치하지 않는다면 그 인덱스의 값의 존재하지 않는다는 뜻으로 그 인덱스를 return 해주었다. 하지만 만약 for문을 다 돌았다는 뜻은 모든 숫자가 존재한다는 뜻이므로 그 다음 숫자가 삽입되야햔다. 그래서 맨 마지막 숫자보다 1만큼 큰 값을 return해준다.