class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if n < 3: return []
res = []
sorted_nums = list(sorted(nums))
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if sorted_nums[i] + sorted_nums[j] + sorted_nums[k] == 0:
if [sorted_nums[i], sorted_nums[j], sorted_nums[k]] not in res:
res.append([sorted_nums[i], sorted_nums[j], sorted_nums[k]])
return res
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# Time complexity: O(n^2)
# Space complexity: O(n)
n = len(nums)
if n < 3: return []
res = []
sorted_nums = list(sorted(nums))
for i in range(n-2):
if i > 0 and sorted_nums[i-1] == sorted_nums[i]: # Skip already found threeSum for a fixed sorted_nums[i]
continue
l, r = i+1, n-1
while l < r:
threeSum = sorted_nums[i] + sorted_nums[l] + sorted_nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
else:
res.append([sorted_nums[i], sorted_nums[l], sorted_nums[r]])
l += 1
while sorted_nums[l] == sorted_nums[l-1] and l < r: # Find all unique threeSum for a fixed sorted_nums[i]
l += 1
return res
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, 2022Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Apr 23, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up