Catalogue
- Assumption
- unsorted or sorted
- return index ? or value ?
- duplicate ?
- size, data type, data range ?
- optimize time or space ?
- How many time are we going to call this function?
2 Sum
$O(n^2)$
###1.Two Sum
Given 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.
- HashTable
1
2
3
4
5
6
7
8
9# Time : O(n), Space : O(n)
class Solution(object):
def twoSum(self, nums, target):
coml = {}
for i in xrange(len(nums)):
c = target-nums[i]
if c in coml:
return [coml[c], i]
coml[nums[i]] = i
- Why not Sort + Two Pointers ?
- after sort, lost the information of indices
- return indice instead of values
167. Two Sum II - Input array is sorted
- Not Zero-Based Index
1
2
3
4
5
6
7
8
9
10
11
12class Solution(object):
def twoSum(self, nums, target):
l = 0
r = len(nums) - 1
while l < r:
s = nums[l] + nums[r]
if s > target:
r -= 1
elif s < target:
l += 1
else:
return [l+1, r+1]
170. Two Sum III - Data structure design
- HashTable, consider duplicates
- Trade Off, quick add or quick find ?
1 | class TwoSum(object): |
653. Two Sum IV - Input is a BST
- This is a general idea for binary tree instead of BST!!!
1 | class Solution(object): |
3 Sum
$O(n^3)$
15. 3Sum
- only one results ? no
- duplicates ? yes
- The solution set must not contain duplicate triplets.
1 | class Solution(object): |
16. 3Sum Closest
1 | class Solution(object): |
4 Sum
$O(n^4)$