📠 문제
- Missing Number
- 난이도: Easy
- 주어진 0부터 n까지 있는 배열에서 비어있는 숫자를 찾는 문제
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.
💡 풀이
이 문제는 아주 단순하게 풀린다. 모든 수를 더하고 배열을 순회하면서 마이너스하면 결국 없는 숫자가 남게 된다. 한줄로 해결도 가능하다! 🎉
func missingNumber(_ nums: [Int]) -> Int {
nums.reduce((nums.count * (nums.count + 1) / 2), -)
}
'→ Problems' 카테고리의 다른 글
[Algorithm] LeetCode - Reorder List (0) | 2025.05.12 |
---|---|
[Algorithm] LeetCode - 3Sum (0) | 2025.05.11 |
[Algorithm] LeetCode - Linked List Cycle (0) | 2025.05.09 |
[Algorithm] LeetCode - Word Break (0) | 2025.05.09 |
[Algorithm] LeetCode - Container With Most Water (0) | 2025.05.08 |