File tree 4 files changed +112
-0
lines changed
find-minimum-in-rotated-sorted-array
maximum-depth-of-binary-tree
4 files changed +112
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(len(coins) * amount)
3
+ Space complexity O(amount)
4
+
5
+ Dynamic programming
6
+ """
7
+
8
+ class Solution :
9
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
10
+ coins = sorted (coins )
11
+
12
+ if amount == 0 :
13
+ return 0
14
+
15
+ dp = [0 ] + [- 1 for _ in range (amount )]
16
+
17
+ for i in range (coins [0 ], amount + 1 ):
18
+ tmp = []
19
+ for x in coins :
20
+ if i - x >= 0 :
21
+ if dp [i - x ] != - 1 :
22
+ tmp .append (dp [i - x ] + 1 )
23
+ if len (tmp ) == 0 :
24
+ dp [i ] = - 1
25
+ else :
26
+ dp [i ] = min (tmp )
27
+
28
+ if dp [- 1 ] == 0 :
29
+ return - 1
30
+ return dp [- 1 ]
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(logn)
3
+ Space compexity O(1)
4
+
5
+ Binary search
6
+ """
7
+
8
+ class Solution :
9
+
10
+ def findMin (self , nums : List [int ]) -> int :
11
+ start = 1
12
+ end = len (nums ) - 1
13
+
14
+ while start <= end :
15
+ mid = (start + end ) // 2
16
+ if nums [mid - 1 ] > nums [mid ]:
17
+ return nums [mid ]
18
+ if nums [0 ] < nums [mid ]:
19
+ start = mid + 1
20
+ else :
21
+ end = mid - 1
22
+
23
+ return nums [0 ]
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n)
3
+ """
4
+ from collections import deque
5
+
6
+ class Solution :
7
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
8
+ if not root :
9
+ return 0
10
+
11
+ max_depth = 0
12
+
13
+ # bfs
14
+ q = deque ([[root , 1 ]])
15
+ while (q ):
16
+ node , depth = q .pop ()
17
+ if max_depth < depth :
18
+ max_depth = depth
19
+ if node .left :
20
+ q .append ([node .left , depth + 1 ])
21
+ if node .right :
22
+ q .append ([node .right , depth + 1 ])
23
+
24
+ return max_depth
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n+m)
3
+ """
4
+
5
+ class Solution :
6
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
7
+ if not (list1 or list2 ):
8
+ return list1 or list2 # if empty list
9
+
10
+ nums = []
11
+ while (list1 or list2 ):
12
+ if not list1 :
13
+ val = list2 .val
14
+ list2 = list2 .next
15
+ elif not list2 :
16
+ val = list1 .val
17
+ list1 = list1 .next
18
+ else :
19
+ if list1 .val <= list2 .val :
20
+ val = list1 .val
21
+ list1 = list1 .next
22
+ else :
23
+ val = list2 .val
24
+ list2 = list2 .next
25
+ nums .append (val )
26
+
27
+ head = ListNode (nums [0 ])
28
+ node = head
29
+ if len (nums ) == 1 :
30
+ return head
31
+ for n in nums [1 :]:
32
+ tmp = ListNode (n )
33
+ node .next = tmp
34
+ node = tmp
35
+ return head
You can’t perform that action at this time.
0 commit comments