- 首先进行排序,这样可以运用双指针,减少遍历的复杂度
- 定义一个变量记录下前一次的和,每次都和前一次的和进行比较,如果更接近target,就进行替换。
- 双指针的移动,去除重复的,查找更快。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
#def nums1(nums,target):
nums.sort()
print(nums)#####################
res = []
temp = []#记录距离
temp_num = []#记录三个数的和
for k in range(len(nums) - 2):
if k > 0 and nums[k] == nums[k - 1]:#去除重复的
continue
# print(nums[k])
# print(nums[i])
# print(nums[j])
i = k + 1
j = len(nums) - 1
# print(nums[k])
# print("#######")
while i < j:
# temp_dis = 0
s = nums[k] + nums[i] + nums[j]
# print(s)
temp_dis = s - target#计算实际值(不取绝对值),为了进行指针的移动,但还是要计算出所有的结果,才可以找出最好的。但是时间复杂度已经变成了n
temp_dis_a = abs(s - target)#记录绝对值,当前结果是否需要替换前面的结果,之保留最有的一个结果
if len(temp) == 0:
temp.append(temp_dis_a)
temp_num.append(s)
# temp_num.append(nums[i])
# temp_num.append(nums[j])
elif temp_dis_a < temp[0]:
temp = []
temp.append(temp_dis_a)
temp_num = []
temp_num.append(s)
# temp_num.append(nums[i])
# temp_num.append(nums[j])
else:
pass
if temp_dis == 0:
return s
elif temp_dis > 0:
j -= 1
while nums[j] == nums[j + 1] and i < j:
j -= 1
else:
i += 1
while nums[i] == nums[i - 1] and i < j:
i += 1
return temp_num[0]```