File tree Expand file tree Collapse file tree 3 files changed +71
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 3 files changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/house-robber/
3+ * time complexity : O(n)
4+ * space complexity : O(n)
5+ */
6+
7+ function rob ( nums : number [ ] ) : number {
8+ const houseCount = nums . length ;
9+
10+ if ( houseCount === 0 ) return 0 ;
11+ if ( houseCount === 1 ) return nums [ 0 ] ;
12+
13+ const maxRobAmount = new Array ( houseCount ) . fill ( 0 ) ;
14+ maxRobAmount [ 0 ] = nums [ 0 ] ;
15+ maxRobAmount [ 1 ] = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
16+
17+ for ( let i = 2 ; i < houseCount ; i ++ ) maxRobAmount [ i ] = Math . max ( maxRobAmount [ i - 1 ] , maxRobAmount [ i - 2 ] + nums [ i ] ) ;
18+
19+ return maxRobAmount [ houseCount - 1 ] ;
20+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3+ * time complexity : O(log n)
4+ * space complexity : O(1)
5+ */
6+
7+ class TreeNode {
8+ val : number
9+ left : TreeNode | null
10+ right : TreeNode | null
11+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
12+ this . val = ( val === undefined ? 0 : val )
13+ this . left = ( left === undefined ? null : left )
14+ this . right = ( right === undefined ? null : right )
15+ }
16+ }
17+
18+ export function lowestCommonAncestor ( root : TreeNode | null , p : TreeNode , q : TreeNode ) : TreeNode | null {
19+ while ( root ) {
20+ if ( p . val < root . val && q . val < root . val ) root = root . left ;
21+ else if ( p . val > root . val && q . val > root . val ) root = root . right ;
22+ else return root ;
23+ }
24+ return null ;
25+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * https://www.lintcode.com/problem/920/
3+ * time complexity : O(n log n)
4+ * space complexity : O(log n)
5+ */
6+
7+ export class Interval {
8+ start : number ;
9+ end : number ;
10+ constructor ( start : number , end : number ) {
11+ this . start = start ;
12+ this . end = end ;
13+ }
14+ }
15+ g
16+ export function canAttendMeetings ( intervals : Interval [ ] ) : boolean {
17+ intervals . sort ( ( a , b ) => a . start - b . start ) ;
18+
19+ for ( let i = 0 ; i < intervals . length - 1 ; i ++ ) {
20+ const { end } = intervals [ i ] ;
21+ const { start : nextStart } = intervals [ i + 1 ] ;
22+
23+ if ( end > nextStart ) return false ;
24+ }
25+ return true ;
26+ }
You can’t perform that action at this time.
0 commit comments