일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- generic
- docker
- security
- loop
- 보안
- npm
- VUE
- dotenv
- bash
- vuetify
- webpack
- vue.js
- C++
- Clone
- leetcode
- machine learning
- TypeScript
- BOJ
- scss
- property
- Python
- condition
- C#
- AI
- type
- 앙상블
- var
- nginx
- git
- JavaScript
Archives
- Today
- Total
ice rabbit programming
[LeedCode] 268. Missing Number 본문
728x90
https://leetcode.com/problems/missing-number/
문제는 매우 직관적으로 이해할 수 있다. 중복이 없는 n 길이의 0~n 배열이 주어지는데, 이 중 한 숫자가 비어 있는데 이를 찾으면 되는 문제이다.
가장 단순하게는 O(n)으로 순회하면서 없는 값을 반환하면 된다.
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(0, len(nums)+1):
if i not in nums:
return i
return 0
O(1)로 풀려면, IQ테스트 같긴 하지만 0부터 n까지의 숫자가 주어진다는 점을 착안하여,1부터 n까지 더한 값과의 차를 구하면 O(1)로 풀 수 있다.
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
return ((n * (n+1)) // 2 ) - sum(nums)
728x90
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 112. Path Sum (0) | 2024.03.07 |
---|---|
[LeetCode] 58. Length of Last Word (0) | 2024.03.07 |
[LeetCode] 258. Add Digits (0) | 2022.11.10 |
[LeetCode] 225. Implement Stack using Queues (0) | 2022.11.10 |
[LeetCode] 232. Implement Queue Using Stacks (0) | 2022.11.10 |