Skip to content

Commit 85f6c91

Browse files
committed
missing-number solution
1 parent 66a9725 commit 85f6c91

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

missing-number/byol-han.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* https://leetcode.com/problems/missing-number/
3+
* @param {number[]} nums
4+
* @return {number}
5+
*/
6+
var missingNumber = function (nums) {
7+
nums.sort((a, b) => a - b);
8+
9+
for (let i = 0; i < nums.length; i++) {
10+
if (nums[i] !== i) {
11+
return i; // 빠진 숫자를 찾으면 리턴
12+
}
13+
}
14+
15+
return nums.length; // 모든 숫자가 다 있으면 빠진 건 n
16+
};
17+
18+
// 수학적 합 공식 이용하기 (가장 빠름)
19+
//시간복잡도: O(n)
20+
// 공간복잡도: O(1) (아주 효율적)
21+
22+
var missingNumber = function (nums) {
23+
const n = nums.length;
24+
const expectedSum = (n * (n + 1)) / 2;
25+
const actualSum = nums.reduce((a, b) => a + b, 0);
26+
return expectedSum - actualSum;
27+
};

0 commit comments

Comments
 (0)