Datawhale leetcode训练营 第七天

题目描述

最接近的三数之和
在这里插入图片描述

方法一:

看到这个就想到昨天的三数之和
不过目的变成到target的距离最小,上一题的target=0
还是借用老表的图解

https://blog.csdn.net/qq_39241986/article/details/83154759

在这里插入图片描述

class Solution(object):
	def threeSumClosest(self, nums, target):
		"""
		:type nums: List[int]
		:type target: int
		:rtype: int
		"""
		# 初始化最大距离
		distance_max = 10000
		# 返回结果
		result_sum = 0
		# 排序,方便比较
		nums.sort()
		# 找第一个数
		for i in range(len(nums)-2):
			left = i + 1
			right = len(nums) - 1
			first = nums[i]
			# 找从左到右和从右到左两边的组合
			while left < right:
				second = nums[left]
				third = nums[right]
				sum = first + second + third
				distance = abs(sum - target)
				if distance == 0: # 最接近
					return target
				elif distance < distance_max: # 距离变小,记录当前sum和distance_max
					result_sum = sum
					distance_t = distance
				if sum > target:
					right -= 1   # 左移变大
				else:
					left += 1    # 右移变小
		return result_sum

七天打卡就这样结束喇,时间过的真快,学到了一点算法的皮毛,感谢大表哥的讲解,希望自己能坚持下去!

猜你喜欢

转载自blog.csdn.net/qq_35547281/article/details/86750922