LeetCode 3Sum Closest
来源:互联网 发布:python 字符串 查找 编辑:程序博客网 时间:2024/05/21 09:10
LeetCode解题之3Sum Closest
原题
找出一个列表中三个元素之和与目标值最接近的情况,并返回这个值。假设整个列表中只有一个最接近的值。
注意点:
- 结果要求返回的是和,而不是三元组
例子:
输入: nums=[1, 1, 1, 1], target=-100
输出: 3
解题思路
思路与3Sum基本相同,现在要额外维护一个表示之前三元组中与目标值的差最小值的变量,这个变量的初始化值应该很大,防止把有意义的三元组直接排除了。此外,由于题目中明确说只有唯一的一组最优解,所有不用考虑重复数字了。
AC源码
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() i = 0 result = 0 # Init the distance between result and target with a very large number distance = pow(2, 32) - 1 for i in range(len(nums)): j = i + 1 k = len(nums) - 1 while j < k: l = [nums[i], nums[j], nums[k]] if sum(l) == target: return target if abs(sum(l) - target) < distance: result = sum(l) distance = abs(sum(l) - target) elif sum(l) > target: k -= 1 else: j += 1 return resultif __name__ == "__main__": assert Solution().threeSumClosest([1, 1, 1, 1], -100) == 3
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- Project Euler-Integer right triangles
- JsplitPane
- 如何将办公文件转换成图片(一) -- 搭建Windows环境下OpenOffice+mupdf+vs2013的开发环境
- wine下玩魔兽的设置
- 数独(九宫格)的高效算法
- LeetCode 3Sum Closest
- System.Data.OracleClient requires Oracle client software version 8.1.7 or greater.
- 基于OpenCV的摄像头脸部识别抓取及格式储存(Python)
- HAProxy 安装与配置
- 不要沦陷程序员30岁问题
- Java中九大内置对象
- explict关键字的含义
- c++/c内部调用TCL
- String类常用方法