1、题目描述
给定一个包括 n 个整数的数组 nums
和 一个目标值 target
。找出 nums
中的三个整数,使得它们的和与 target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
2、题解
2.1、解法一
class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ n = len(nums) print(n) if n < 3: return 0 new_nums = sorted(nums) avg = target/3 max_num = max(new_nums) min_num = min(new_nums) if avg >= max_num: return new_nums[n-3] + new_nums[n-2] + new_nums[n-1] elif avg <= min_num: return new_nums[0] + new_nums[1] + new_nums[2] else: sum_list = [] for i in range(n-2): left = i+1 right = n-1 while left < right: s = new_nums[i] + new_nums[left] + new_nums[right] sum_list.append(s) if new_nums[i] + new_nums[left] + new_nums[right] > target: right -= 1 elif new_nums[i] + new_nums[left] + new_nums[right] < target: left += 1 else: return target sum_list.append(s) return min(sum_list, key=lambda x: abs(target - x))
2.2、解法二
class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ n = len(nums) print(n) if n < 3: return 0 nums.sort() print(nums) sum_list = [] for i,num in enumerate(nums[0:-2]): l, r = i + 1, n - 1 # 最大的情况小于target,其他的无需比较 if num + nums[r-1] + nums[r] <= target: sum_list.append(num + nums[r-1] + nums[r]) # 最小的情况大于target,其他的无需比较 elif num + nums[l] + nums[l+1] >= target: sum_list.append(num + nums[l] + nums[l+1]) # 中间情况 else: while l < r: print(i,l,r,num + nums[l] + nums[r]) sum_list.append(num + nums[l] + nums[r]) if num + nums[l] + nums[r] > target: r -= 1 elif num + nums[l] + nums[r] < target: l += 1 else: return target print(sum_list) # return min(sum_list, key=lambda x: abs(target - x)) sum_list.sort(key=lambda x: abs(target - x)) print(sum_list) return sum_list[0]