1. Two Sum(https://oj.leetcode.com/problems/two-sum/)
解题思路:
解法一: 暴力,O(n2)时间复杂度,TLE
解法二:利用hash, 记录下数组中每个值对应的下标,再遍历一遍数组,通过查看target-num[i]的值是否在map中来确定另一个数值。时间复杂度O(n)
解法三:对num数组排序,O(nlog(n)), 然后左右夹逼O(n). 但这道题要求记录下标,故这个方法行不通。
python代码如下:
1 def twoSum(self, num, target): 2 d = {} 3 lenNum = len(num) 4 ans = [] 5 for i in xrange(lenNum): 6 d[num[i]] = [i+1] if num[i] not in d else d[num[i]] + [i+1] 7 for i in num: 8 res = target - i 9 if res in d: 10 if res == i: 11 if len(d[i]) == 2: return (d[i][0], d[i][1]) 12 else: 13 return (d[i][0], d[res][0]) if d[i][0] < d[res][0] else (d[res][0], d[i][0])
2. 3Sum(https://oj.leetcode.com/problems/3sum/)
(1)对num进行排序
(2)取一个元素a, 从a的下一个元素到数组的末尾,采用两端夹逼的方法,找到b, c符合b+c=target-a
(3)此过程中注意去重
(4)时间复杂度O(n^2)
1 def threeSum(self, num): 2 res = [] 3 lenNum = len(num) 4 if lenNum < 2: return res 5 num.sort() 6 for i in xrange(lenNum-2): 7 a = num[i] 8 if i > 0 and a == num[i-1]: 9 continue 10 left = i+1; right = lenNum-1 11 while left < right: 12 b = num[left] 13 c = num[right] 14 if b + c == -a: 15 res.append([a, b, c]) 16 while left < right: 17 left += 1 18 right -= 1 19 if num[left] != b or num[right] != c: 20 break 21 elif b + c < -a: 22 while left < right: 23 left += 1 24 if num[left] != b: 25 break 26 else: 27 while left < right: 28 right -= 1 29 if num[right] != c: 30 break 31 return res
3. 3Sum Closest(https://oj.leetcode.com/problems/3sum-closest/)
(1)对num进行排序
(2)先取定a, 采用两端夹逼的方法取b, c, 计算sum=a+b+c, 维护mindiff=target-sum,若碰到sum=target,则立即返回0。
(3)时间复杂度O(n^2)
def threeSumClosest(self, num, target): res = [] num.sort() mindiff = 100000 lenNum = len(num) for i in xrange(lenNum-2): a = num[i] left = i+1 right = lenNum-1 while left < right: b = num[left] c = num[right] sum = a + b + c diff = abs(target - sum) if diff < mindiff: mindiff = diff; res = sum if sum < target: left += 1 elif sum > target: right -= 1 else: return sum return res
4. 4Sum(https://oj.leetcode.com/problems/4sum/)
(1)对num进行排序
(2)使用dict,存储dict[num[i]+num[j]]=([i,j]), key为num[i]+num[j], value为[[i,j]]即下标。
(3)两层循环, p, q, num[p] < num[q], 则在dict中找key为target-num[p]-num[q]的value,且q < i
(4)时间复杂度O(n^2)
1 def fourSum(self, num, target): 2 num.sort() 3 res = set() 4 lenNum = len(num) 5 dict = {} 6 for i in xrange(lenNum): 7 for j in xrange(i+1, lenNum): 8 key = num[i] + num[j] 9 if key not in dict: 10 dict[key] = [(i, j)] 11 else: 12 dict[key].append((i, j)) 13 14 for p in xrange(lenNum): 15 for q in xrange(p+1, lenNum): 16 key = target - num[p] - num[q] 17 if key in dict: 18 for value in dict[key]: 19 if q < value[0]: 20 res.add((num[p], num[q], num[value[0]], num[value[1]])) 21 return [list(i) for i in res]