Skip to content

Commit 4aba7a6

Browse files
author
zongyanqi
committed
add Easy_268_Missing_Number
1 parent 293b271 commit 4aba7a6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Easy_268_Missing_Number.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
*
3+
* Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
4+
* find the one that is missing from the array.
5+
* For example,
6+
* Given nums = [0, 1, 3] return 2.
7+
*
8+
* Note:
9+
* Your algorithm should run in linear runtime complexity.
10+
* Could you implement it using only constant extra space complexity?
11+
*
12+
*
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @return {number}
18+
*/
19+
var missingNumber = function (nums) {
20+
var n = nums.length;
21+
var ideal = n * (n + 1) / 2;
22+
var sum = nums.reduce((a, b)=> a = a + b, 0);
23+
return ideal - sum;
24+
};
25+
26+
console.log(missingNumber([0, 1, 3]) == 2);
27+
console.log(missingNumber([0, 1, 2]) == 3);
28+
console.log(missingNumber([1, 2, 3, 4]) == 0);
29+
30+

0 commit comments

Comments
 (0)