File tree 4 files changed +94
-0
lines changed
binary-tree-level-order-traversal 4 files changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ // TC: O(n)
2
+ // need to visit all nodes
3
+ // SC: O(n)
4
+ // normally O(log n) required however, O(n) in the worst case
5
+ class Solution {
6
+ private List <List <Integer >> output = new ArrayList <>();
7
+ public List <List <Integer >> levelOrder (TreeNode root ) {
8
+ dfs (0 , root );
9
+ return output ;
10
+ }
11
+
12
+ private void dfs (int level , TreeNode node ) {
13
+ if (node == null ) return ;
14
+
15
+ if (output .size () == level ) {
16
+ List <Integer > inside = new ArrayList <>();
17
+ inside .add (node .val );
18
+ output .add (inside );
19
+ } else {
20
+ output .get (level ).add (node .val );
21
+ }
22
+ level += 1 ;
23
+ dfs (level , node .left );
24
+ dfs (level , node .right );
25
+ }
26
+ }
Original file line number Diff line number Diff line change
1
+ // TC: O(n)
2
+ // visit all nums at least once
3
+ // SC: O(1)
4
+ // only constant memory space required
5
+ class Solution {
6
+ public int rob (int [] nums ) {
7
+ if (nums .length == 1 ) return nums [0 ];
8
+
9
+ int prev = 0 ;
10
+ int post = 0 ;
11
+ int output1 = 0 ;
12
+
13
+ for (int i = 0 ; i < nums .length - 1 ; i ++) {
14
+ int temp = prev ;
15
+ prev = Math .max (post + nums [i ], prev );
16
+ post = temp ;
17
+ }
18
+ output1 = prev ;
19
+
20
+ prev = 0 ;
21
+ post = 0 ;
22
+ int output2 = 0 ;
23
+ for (int i = 1 ; i < nums .length ; i ++) {
24
+ int temp = prev ;
25
+ prev = Math .max (post + nums [i ], prev );
26
+ post = temp ;
27
+ }
28
+ output2 = prev ;
29
+
30
+ return Math .max (output1 , output2 );
31
+ }
32
+ }
Original file line number Diff line number Diff line change
1
+ // TC: O(n)
2
+ // visit all intervals to compare each of start time
3
+ // SC: O(n)
4
+ // PQ save all intervals in the worst case
5
+ public class Solution {
6
+ public int minMeetingRooms (List <Interval > intervals ) {
7
+ if (intervals == null || intervals .isEmpty ()) return 0 ;
8
+
9
+ intervals .sort ((a , b ) -> a .start - b .start );
10
+
11
+ PriorityQueue <Integer > endTimes = new PriorityQueue <>();
12
+ endTimes .add (intervals .get (0 ).end );
13
+
14
+ for (int i = 1 ; i < intervals .size (); i ++) {
15
+ Interval current = intervals .get (i );
16
+ if (current .start >= endTimes .peek ()) endTimes .poll ();
17
+ endTimes .add (current .end );
18
+ }
19
+
20
+ return endTimes .size ();
21
+ }
22
+ }
Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public int reverseBits (int n ) {
3
+ // time complexity O(1)
4
+ // space complexity O(1)
5
+ int output = 0 ;
6
+
7
+ for (int i = 0 ; i < Integer .SIZE ; i ++) {
8
+ output <<= 1 ;
9
+ output += n & 1 ;
10
+ n >>= 1 ;
11
+ }
12
+ return output ;
13
+ }
14
+ }
You can’t perform that action at this time.
0 commit comments