Leetcode=最接近的三数之和
2019-02-02 16:24
323 查看
Leetcode=最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
解决方法:类似题库14三数之和的方法,先排序,然后遍历数组,找另外两个数left和right,判断三数之和和target的距离,如果小就left++,如果大就right–。
class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() length = len(nums) min_val = float("inf") res = 0 for i in range(length - 2): l = i + 1 r = length - 1 while l < r: sum_val = nums[i] + nums[l] + nums[r] if sum_val - target == 0: return target if abs(sum_val - target) < min_val: min_val = abs(nums[i] + nums[l] + nums[r] - target) res = sum_val if sum_val > target: r -= 1 else: l += 1 return res
相关文章推荐
- [LeetCode] 16. 3Sum Closest 最接近的三数之和 @python
- LeetCode题解(python)-16. 最接近的三数之和
- LeetCode刷题-最接近的三数之和
- LeetCode 16. 最接近的三数之和
- LeetCode——16. 最接近的三数之和
- leetcode 16. 最接近的三数之和(Java版)
- leetcode 16 最接近的三数之和
- 最接近的三数之和 - LeetCode
- LeetCode16-最接近的三数之和
- leetcode16---最接近的三数之和
- leetcode第16题,最接近的三数之和,python实现
- leetcode 16 最接近的三数之和
- Leetcode刷题38-16.最接近的三数之和(C++)
- 【Leetcode】16. 最接近的三数之和
- LeetCode16. python实现:最接近的三数之和问题☆☆
- LeetCode16.最接近的三数之和
- LeetCode 16. 3Sum Closest. (最接近的三数之和)
- LeetCode- 16. 最接近的三数之和 (Medium)python和c++实现
- 【PHP解法==LeetCode查找类型问题2(N数之和)】15.三数之和 && 16.最接近的三数之和 && 18.四数之和 && 454.四数相加II
- 【LeetCode-面试算法经典-Java实现】【016-3 Sum Closest(最接近的三个数的和)】