File tree Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def containsDuplicate (self , nums : List [int ]) -> bool :
3+ # Slow - tc : O(n) / sc : O(1)
4+
5+ """return len(set(nums)) != len(nums)"""
6+
7+ # Fast - tc : O(n) / sc : O(n)
8+ check = set ()
9+
10+ for num in nums :
11+ if num in check :
12+ return True
13+ check .add (num )
14+
15+ return False
16+
17+
18+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def bfs (self , nums ):
3+ from collections import deque
4+ queue = deque ()
5+
6+ # price, idx, robbed prev
7+ queue .append ([0 , 0 , False ])
8+ queue .append ([0 , 0 , True ])
9+ ret = 0
10+
11+ while queue :
12+ price , idx , prev = queue .popleft ()
13+ ret = max (ret , price )
14+ if idx == len (nums ):
15+ continue
16+
17+ if prev :
18+ queue .append ([price , idx + 1 , False ])
19+ else :
20+ queue .append ([price , idx + 1 , False ])
21+ queue .append ([price + nums [idx ], idx + 1 , True ])
22+
23+ return ret
24+
25+ def rob (self , nums : List [int ]) -> int :
26+ # BFS - Slow and out of memory
27+ """return self.bfs(nums)"""
28+
29+ # DP
30+ n = len (nums )
31+ record = [[0 ]* n for _ in range (2 )]
32+ record [1 ][0 ] = nums [0 ]
33+
34+ for i in range (1 , n ):
35+ record [1 ][i ] = max (record [0 ][i - 1 ]+ nums [i ], record [1 ][i ])
36+ record [0 ][i ] = max (record [1 ][i - 1 ], record [0 ][i - 1 ])
37+
38+ return max (record [1 ][- 1 ], record [0 ][- 1 ])
39+
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
3+ # Naive Solution
4+ # TC : O(nlogn)
5+ # SC : O(n)
6+
7+ cnt = dict ()
8+ for num in nums :
9+ cnt [num ] = cnt .get (num , 0 ) + 1
10+
11+ """
12+ ret = dict(sorted(cnt.items(), key=lambda x:(-x[1], x[0])))
13+ return list(ret.keys())[:k]
14+ """
15+
16+ # Follow up Solution
17+ # TC : O(nlog(k))
18+ # SC : O(n)
19+
20+ import heapq
21+
22+ ret = [(- c , num ) for num , c in cnt .items ()]
23+ heapq .heapify (ret )
24+
25+ return [heapq .heappop (ret )[1 ] for _ in range (k )]
26+
Original file line number Diff line number Diff line change 1+ import re
2+
3+ class Solution :
4+ def isPalindrome (self , s : str ) -> bool :
5+ # Fastest - tc : O(n) / sc : O(1
6+ s = '' .join (re .findall (r'[a-z0-9]+' , s .lower ()))
7+ return s == '' .join (reversed (s ))
You can’t perform that action at this time.
0 commit comments