16 3 Sum Closest
使用defaultdict 建立一个保存closest值的一个字典(相当于哈希表, 每次使用这个hash表进行更新操作
from collections import defaultdict
class Solution:
def threeSumClosest(self, nums: 'List[int]', target: 'int') -> 'int':
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
length = len(nums)
resultList = []
d = defaultdict(int)
nums.sort()
for i in range(0,length-2):
j = i + 1
k = length - 1
while (j < k):
sums = nums[i] + nums[j] + nums[k]
if sums == target:
return target
elif sums < target:
j += 1
else:
k -= 1
d[abs(sums-target)] = sums
return d[min(d.keys())]