Question 1b 2 Sum II
clarification of problems
sorted or unsorted
duplicate?
我们其实是for each j,
去找smallest i, s.t. array[i] >= target - array[j]
Sorted array, no duplicate
Method 1 Brute Force
check all pair (i, j) see if array[i] + array[j] = target
如何找,需要让pair有顺序出现
所以可以用i < j (小trick,固定大的找小的,大多数时候会比较的方便)
所以相当于在找array[i] == target - array[j]
smallest array[i] >= target - array[j]
option 1: binary search using sorted array
option 2: HashSet record all the elements before j
option 3: 相向而行的two pointer
Sorted array, duplicate not count
Sorted array, duplicated elements count
唯一区别,就是多count
[1,1,2,2,2,2,2,3,3,3,3] taregt 4, return 18
Unsorted array # of pairs sum to target
有多少index i such that i < j.
在[0, j - 1] 有多少个元素,值是target- array[j]
优化这一步,怎么做,需要用什么数据结构做,数据结果存什么?
Last updated