https://leetcode.com/problems/longest-consecutive-sequence/
curr_num
gets incremented n times (worse case)curr_num + 1 in nums
is O(n)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
maxCount = 0
for num in nums:
curr_num = num
count = 1
while curr_num + 1 in nums:
curr_num += 1
count += 1
maxCount = max(maxCount, count)
return maxCount
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
sorted_nums = sorted(nums)
maxCount, count = 0, 1
for i in range(len(sorted_nums)-1):
if sorted_nums[i] != sorted_nums[i+1]:
if abs(sorted_nums[i] - sorted_nums[i+1]) == 1:
count += 1
else:
maxCount = max(maxCount, count)
count = 1
return max(maxCount, count)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
maxCount = 0
nums_set = set(nums)
for num in nums:
if num - 1 in nums_set:
# no need for current num to start its own sequence
# because it is already part of a longest consecutive
# elements sequence
continue
else:
curr_num = num
count = 1
while curr_num + 1 in nums_set:
curr_num += 1
count += 1
maxCount = max(maxCount, count)
return maxCount
https://leetcode.com/problems/find-k-closest-elements/ Naive def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: L = sorted([(abs(elt - x), elt) for elt in arr], key=lambda tup: tup[0]) return sorted([tup[1] for tup in L[:k]]) Opti
Sep 23, 2022Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack();
Jun 27, 2022Given a string containing just the characters $($, $)$, ${$, $}$, $[$ and $]$, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Jun 27, 2022Solution 1 Time complexity: O(n³) Space complexity: O(n) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return []
Apr 23, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up