forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnaringst.js
More file actions
62 lines (52 loc) · 1.05 KB
/
naringst.js
File metadata and controls
62 lines (52 loc) · 1.05 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @param {number[]} nums
* @return {number}
*/
/**
* Runtime: 63ms, Memory: 51.68MB
* Time complexity: O(nlogn)
* Space complexity: O(nlogn)
*
*/
var missingNumber = function (nums) {
const n = nums.length;
nums.sort((a, b) => a - b);
if (!nums.includes(0)) {
return 0;
}
for (let i = 0; i < n; i++) {
if (nums[i + 1] - nums[i] !== 1) {
return nums[i] + 1;
}
}
return nums[-1];
};
/**
* NOTE
* if use 'sort()' -> O(nlogn)
* if you solve this problem without using sort(), can use sum of nums
*/
var missingNumber = function (nums) {
const sumOfNums = nums.reduce((num, total) => num + total, 0);
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
if (expectedSum === sumOfNums) {
return 0;
} else {
return expectedSum - sumOfNums;
}
};
/**
* NOTE
* or you can subtract while adding
*/
var missingNumber = function (nums) {
let target = 0;
for (let i = 0; i <= nums.length; i++) {
target += i;
if (i < nums.length) {
target -= nums[i];
}
}
return target;
};