diff --git a/contains-duplicate/i-mprovising.py b/contains-duplicate/i-mprovising.py new file mode 100644 index 000000000..4b0c12beb --- /dev/null +++ b/contains-duplicate/i-mprovising.py @@ -0,0 +1,11 @@ +""" +O(n) complexity +""" + + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + nums_set = set(nums) + if len(nums) == len(nums_set): + return False + return True diff --git a/house-robber/i-mprovising.py b/house-robber/i-mprovising.py new file mode 100644 index 000000000..475001182 --- /dev/null +++ b/house-robber/i-mprovising.py @@ -0,0 +1,21 @@ +""" +Time complexity O(n) +""" + +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + if n == 1: + return nums[0] + dp = [nums[0], max([nums[0], nums[1]])] + if n == 2: + return dp[1] + + for i in range(2, n): + num = nums[i] + tmp = [ + dp[i-2] + num, + dp[i-1] + ] + dp.append(max(tmp)) + return dp[-1] diff --git a/longest-consecutive-sequence/i-mprovising.py b/longest-consecutive-sequence/i-mprovising.py new file mode 100644 index 000000000..5f9c16c53 --- /dev/null +++ b/longest-consecutive-sequence/i-mprovising.py @@ -0,0 +1,19 @@ +""" +Time complexity O(n) +""" + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + num_set = set(nums) # hash table + longest = 0 + + for n in num_set: + if n-1 in num_set: + continue + cur_len = 1 + while n + cur_len in num_set: + cur_len += 1 + + longest = max(longest, cur_len) + + return longest diff --git a/top-k-frequent-elements/i-mprovising.py b/top-k-frequent-elements/i-mprovising.py new file mode 100644 index 000000000..25a96d1a3 --- /dev/null +++ b/top-k-frequent-elements/i-mprovising.py @@ -0,0 +1,11 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + """O(nlogn) complexity""" + frequency = defaultdict(int) + for n in nums: + frequency[n] += 1 + sorted_frequency = sorted(frequency.items(), key=lambda x:x[1], reverse=True) + answer = [] + for i in range(k): + answer.append(sorted_frequency[i][0]) + return answer diff --git a/two-sum/i-mprovising.py b/two-sum/i-mprovising.py new file mode 100644 index 000000000..e28492032 --- /dev/null +++ b/two-sum/i-mprovising.py @@ -0,0 +1,12 @@ +""" +hash table +O(n) complexity +""" + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + table = {num:idx for idx, num in enumerate(nums)} + for i, x in enumerate(nums): + y = target - x + if (y in table) and table[y] != i: + return [i, table[y]]