1. input array not sorted
2. looking for 2 numbers, cannot use the element multiple times
3. exactly 1 answer (index)
Dictionary
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if target-nums[i] in dic:
return [dic[target-nums[i]], i]
dic[nums[i]] = i
167. Two Sum II - Input array is sorted
1. the input array is sorted
2. result is not zero-based
Two Pointers O(n)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l, r = 0, len(numbers)-1
while l<r:
s = numbers[l] + numbers[r]
if s == target:
return [l+1, r+1]
elif s<target:
l+=1
else:
r-=1
Binary Search O(n logn)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
n = len(numbers)
for i in range(n-1):
tmp = target-numbers[i]
l, r = i+1, n
while l<r:
mid = l+(r-l)//2
if numbers[mid]==tmp:
return [i+1, mid+1]
elif numbers[mid]<tmp:
l = mid+1
else:
r = mid
Is there a logN solution?
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51251/A-O(logN)-binary-search-Java-Solution-0ms-beat-98
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51378/Share-my-C%2B%2B-O(log2-n)-solution
170. Two Sum III - Data structure design
More Find than Add - TLE
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.n = set()
self.s = set()
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
if number in self.n:
self.s.add(2*number)
else:
for i in self.n:
self.s.add(number+i)
self.n.add(number)
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
return value in self.s
More Add than Find
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.n = {}
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.n[number] = self.n.get(number, 0)+1
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
for i in self.n:
if value-i in self.n:
if i==value-i:
if self.n[i]>1:
return True
else:
return True
return False
optimize with lots of same Find
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.n = {}
self.s = set()
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.n[number] = self.n.get(number, 0)+1
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
if value in self.s: return True
for i in self.n:
if value-i in self.n:
if i==value-i:
if self.n[i]>1:
return True
else:
self.s.add(value)
return True
return False
653. Two Sum IV - Input is a BST
Set - valid for any tree
DFS, Recursion
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
s =set()
return self.dfs(root, k, s)
def dfs(self, root, k, s):
if not root: return False
if k-root.val in s:
return True
s.add(root.val)
return self.dfs(root.left, k, s) or self.dfs(root.right, k, s)
BFS
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
q = collections.deque([root])
s = set()
while q:
t = q.popleft()
if not t: continue
if k-t.val in s:
return True
s.add(t.val)
q.append(t.left)
q.append(t.right)
return False
Two Pointer
stack
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
backward_stack = []
forward_stack = []
p = root
while p:
backward_stack.append(p)
p = p.right
p = root
while p:
forward_stack.append(p)
p = p.left
while backward_stack and forward_stack:
top_b = backward_stack[-1]
top_f = forward_stack[-1]
if top_b.val == top_f.val: break
s = top_b.val+top_f.val
if s==k: return True
elif s>k:
p = backward_stack.pop().left
while p:
backward_stack.append(p)
p = p.right
else:
p = forward_stack.pop().right
while p:
forward_stack.append(p)
p = p.left
return False
iterator
able to use element more than one time
all the answers