[LeetCode] 3Sum Closest 最近的三数之和 Python
来源:互联网 发布:苹果cms整合解析插件 编辑:程序博客网 时间:2024/04/29 23:35
3Sum Closest:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
简单来说,寻找三数之和最接近target的答案,例子如下:
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解决方法:
和 上一篇3Sum的想法类似,因此代码也是在那个的基础上修改的。只不过因为需要求最近的,而不是固定的,因此所有的判定都需要修改为判断与与target做差后的绝对值, 因为代码大构架和3Sum类似,因此时间复杂度还是O(N^2),代码如下:
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() first=[] i=0 Max=0 while(i<len(nums)-2): if(nums[i]!=nums[i-1] or i==0): left=i+1 right=len(nums)-1 while(left<right): if(abs(nums[left]+nums[right]+nums[i]-target)==0): Max=target break if(i==0 and left==1 and right==len(nums)-1): Max=nums[left]+nums[right]+nums[i] if(abs(nums[left]+nums[right]+nums[i]-target)<abs(Max-target)): first.append([nums[i],nums[left],nums[right]]) Max=nums[left]+nums[right]+nums[i] while(left<right and nums[left]+nums[right]+nums[i]<target): left+=1 if(nums[left]!=nums[left-1]): break while(left>right and nums[left]+nums[right]+nums[i]>target): right-=1 if(nums[right]!=nums[right+1]): break elif(nums[left]+nums[right]+nums[i]>target): right-=1 elif(nums[left]+nums[right]+nums[i]<target): left+=1 i+=1 return Max
阅读全文
0 0
- [LeetCode] 3Sum Closest 最近的三数之和 Python
- 3Sum Closest(离目标值最近的三数之和)
- leetCode 16.3Sum Closest (离给定值最近的三数之和) 解题思路和方法
- LeetCodet题解--16. 3Sum Closest(离给定值最近的三数之和)
- [LeetCode] 3Sum 三数之和 Python
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- Leetcode: 15. 3Sum 三数之和
- leetcode-3sum 三数之和
- 【Leetcode】【python】3Sum Closest
- 59.3Sum Closest-最接近的三数之和(中等题)
- Leetcode #16 3Sum Closest 找3数之和最接近 解题小节
- Leetcode #15 3Sum 三数之和 解题小节
- LeetCode 15. 3Sum(三数之和)
- [Leetcode P15] Three Sum 三数之和
- 3Sum Closest 三数最接近
- 16. 3Sum Closest Leetcode Python
- 3Sum Closest Leetcode Python Java
- [leetcode: Python]16. 3Sum Closest
- 汤圆の拯救计划
- fireworks----乘法逆元求组合数(2017山东ACM-ICPC省赛)
- 防止umeditor存数据库时被解析
- 开始吧~
- 前端最全的 API 集锦
- [LeetCode] 3Sum Closest 最近的三数之和 Python
- 经典二分查找问题
- androidannotations中的注解大全
- 解决 java.net.ConnectException: Connection refused: connect 异常
- sklearn学习笔记-《模型验证方法》
- 使用OkHttp
- unity导出安卓APK后图片错乱的解决办法--getResources().getIdentifier()的使用
- 线程,死锁
- 51nod_1247可能的路径