题目链接:
https://leetcode.com/problems/3sum-closest/
input:
nums
= [-1, 2, 1, -4]
,
target
= 1
output:
2
即 (-1 + 2 + 1 = 2).
特殊情况:
- 输入列表中包含重复值,如
nums
=[1,1,1,1]
,target
=0
,output:3 - 要找的是最接近的值,并不一定能找到
target
解题思路
- 使用宽度优先的算法,先计算两个数的和,在计算三个数的和,之后对三个数的和进行检查,找到最接近
target
的值返回。 - 由于
nums
中会有重复值,所以不可直接去重。
code
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
two_map={}
two_dump_map={}
clean_two_map={}
three_map={}
three_dump_map={}
num_size=len(nums)
nums.sort()
#print(num_size)
# 计算两个数的和
for i,n1 in enumerate(nums) :
for j,n2 in enumerate(nums[i+1:]):
val=n2+n1
#去掉会发生重复的部分
# if val in two_dump_map:
# two_dump_map[val]+=1
# continue
# if val in two_map:
# del two_map[val]
# two_dump_map[val]=2
# continue
two_map[val]=[i,i+j+1]
print(two_map)
print(two_dump_map)
del two_dump_map
max_val=target-nums[0]
min_val=target+nums[-1]
#去掉会越界的数
for val in list(two_map.keys()):
if min_val<= val <= max_val:
clean_two_map[val]=two_map[val]
#print(two_map)
#print(clean_two_map)
for i,n3 in enumerate(nums) :
for val,l in two_map.items():
if i not in l:
three_val=val+n3
#找到这个值
if three_val ==target:
return three_val
# if three_val in three_dump_map:
# three_dump_map[three_val]+=1
# continue
# if three_val in three_map:
# three_dump_map[three_val]=2
# continue
three_map[three_val]=[l[0],l[1],i]
#print(three_map)
#print(three_dump_map)
#未找到这个值,找最接近的值
min=sys.maxsize
val=0
#删除重复
# for k,v in three_dump_map.items():
# if v > 3:
# del three_map[k]
#计算最接近的值
for v in three_map.keys():
if abs(v-target) < min:
min=abs(v-target)
val=v
return val