File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @return {number }
4
+ */
5
+
6
+ /**
7
+ * Runtime: 63ms, Memory: 51.68MB
8
+ * Time complexity: O(nlogn)
9
+ * Space complexity: O(nlogn)
10
+ *
11
+ */
12
+
13
+ var missingNumber = function ( nums ) {
14
+ const n = nums . length ;
15
+ nums . sort ( ( a , b ) => a - b ) ;
16
+
17
+ if ( ! nums . includes ( 0 ) ) {
18
+ return 0 ;
19
+ }
20
+ for ( let i = 0 ; i < n ; i ++ ) {
21
+ if ( nums [ i + 1 ] - nums [ i ] !== 1 ) {
22
+ return nums [ i ] + 1 ;
23
+ }
24
+ }
25
+ return nums [ - 1 ] ;
26
+ } ;
27
+
28
+ /**
29
+ * NOTE
30
+ * if use 'sort()' -> O(nlogn)
31
+ * if you solve this problem without using sort(), can use sum of nums
32
+ */
33
+
34
+ var missingNumber = function ( nums ) {
35
+ const sumOfNums = nums . reduce ( ( num , total ) => num + total , 0 ) ;
36
+
37
+ const n = nums . length ;
38
+ const expectedSum = ( n * ( n + 1 ) ) / 2 ;
39
+
40
+ if ( expectedSum === sumOfNums ) {
41
+ return 0 ;
42
+ } else {
43
+ return expectedSum - sumOfNums ;
44
+ }
45
+ } ;
You can’t perform that action at this time.
0 commit comments