File tree 3 files changed +56
-0
lines changed
product-of-array-except-self 3 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/climbing-stairs
3
+ * time complexity : O(n)
4
+ * space complexity : O(1)
5
+ */
6
+
7
+ export const upStairs = ( n : number ) : number => {
8
+ let [ l , r ] = [ 1 , 2 ] ;
9
+ for ( let i = 3 ; i <= n ; i ++ ) [ l , r ] = [ r , l + r ] ;
10
+
11
+ return r ;
12
+ } ;
13
+
14
+ export function climbStairs ( n : number ) : number {
15
+ if ( n <= 2 ) return n ;
16
+ return upStairs ( n ) ;
17
+ } ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/product-of-array-except-self
3
+ * time complexity : O(n)
4
+ * space complexity : O(1)
5
+ */
6
+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
7
+ const n = nums . length ;
8
+ const answer = new Array ( n ) . fill ( 1 ) ;
9
+
10
+ let leftProduct = 1 ;
11
+ for ( let i = 0 ; i < n ; i ++ ) {
12
+ answer [ i ] = leftProduct ;
13
+ leftProduct *= nums [ i ] ;
14
+ }
15
+
16
+ let rightProduct = 1 ;
17
+ for ( let i = n - 1 ; i >= 0 ; i -- ) {
18
+ answer [ i ] *= rightProduct ;
19
+ rightProduct *= nums [ i ] ;
20
+ }
21
+
22
+ return answer ;
23
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/two-sum
3
+ * time complexity : O(n)
4
+ * space complexity : O(n)
5
+ */
6
+ function twoSum ( nums : number [ ] , target : number ) : number [ ] {
7
+ const m = new Map < number , number > ( ) ;
8
+
9
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
10
+ if ( m . has ( nums [ i ] ) )
11
+ return [ m . get ( nums [ i ] ) , i ] ;
12
+ m . set ( target - nums [ i ] , i ) ;
13
+ }
14
+
15
+ return [ - 1 , - 1 ] ;
16
+ } ;
You can’t perform that action at this time.
0 commit comments