LeetCode[Array]----3Sum Closest
来源:互联网 发布:宁波行知小学怎么样 编辑:程序博客网 时间:2024/05/01 08:50
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.
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一题的升级版。题意为在给定数组中找到三个元素a,b,c,使得a + b + c的和最接近给定的target,返回a + b + c。
题目限定了这个三个元素一定能够找到并且唯一。
这里我们借鉴3Sum一题的思路,还是对数组nums进行排序,然后使用双指针进行遍历。
但是与上一题不一样的是,我们这里找到的三个元素和一般来说不会等于target,如果三元素和nsum大于target,那么右指针向左移动,降低nsum值;如果nsum值小于target,那么左指针向右移动,增加nsum值;当然,如果nsum等于target,那么直接返回nsum就好了。通过两个指针的移动,可以使得nsum不断的逼近target。
在指针的移动过程中,我们需要实时记录当前的nsum和target的差值,从中选择差值绝对值最小的nsum为最接近target的和的结果。
相应的代码为:
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ dmin = float('inf') nums.sort() for i in range(len(nums) - 2): left = i + 1 right = len(nums) - 1 while left < right: nsum = nums[left] + nums[right] + nums[i] if abs(nsum - target) < abs(dmin): dmin = nsum - target minsum = nsum if nsum > target: right -= 1 if nsum < target: left += 1 if nsum == target: return nsum return minsum
0 0
- LeetCode[Array]----3Sum Closest
- 16. 3Sum Closest leetcode(array)
- leetcode.array--16. 3Sum Closest
- [Array]3Sum Closest
- 【leetcode】Array——3Sum Closest(16)
- 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
- FOJ 2216 The Longest Straight 第六届福建省大学生程序设计竞赛 E 尺取法乱搞
- 网络流题集合
- 实用的Githup上的iOS开源项目
- windows jenkins
- R语言︱数据去重
- LeetCode[Array]----3Sum Closest
- C/C++调用Matlab程序
- 哈希表及处理冲突的方法
- 为什么中国的程序员总被称为码农?
- 数组的实质
- Matlab中的线型、标记和颜色
- 由于丢失OLR导致的节点无法启动
- 查看mysql 用户所拥有权限
- 递归查询网页Frame