每日算法系列【LeetCode 16】最接近的三数之和

简介: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

题目描述


给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例1

输入:
nums = [-1,2,1,-4], target = 1.
输出:
2
解释:
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

题解


image.png

代码


c++

classSolution {
public: 
intthreeSumClosest(vector<int>&nums, inttarget) { 
intn=nums.size(), res=10000000;  
sort(nums.begin(), nums.end()
            );    
for (inti=0; i<n-2; ++i) {
intl=i+1, r=n-1;  
while (l<r) {  
intsum=nums[i] +nums[l] +nums[r]; 
if (sum==target) returnsum;  
if (abs(sum-target) <abs(res-target)) res=sum;
if (sum>target) r--;   
elsel++;     
            }     
        }    
returnres;  
    }
};

python

classSolution: 
defthreeSumClosest(self, nums: List[int], target: int) ->int:        n, res=len(nums), 10000000nums.sort() 
foriinrange(n-2):  
l, r=i+1, n-1whilel<r:  
s=nums[i] +nums[l] +nums[r]    
ifs==target:  
returnsifabs(s-target) <abs(res-target):   
res=sifs>target: 
r-=1else:      
l+=1returnres

image.png

作者简介:godweiyang知乎同名华东师范大学计算机系硕士在读,方向自然语言处理与深度学习喜欢与人分享技术与知识,期待与你的进一步交流~


相关文章
|
8天前
|
存储 算法 数据挖掘
LeetCode第十六题: 掌握双指针技巧 最接近的三数之和 【python】
LeetCode第十六题: 掌握双指针技巧 最接近的三数之和 【python】
|
1月前
leetcode-16:最接近的三数之和
leetcode-16:最接近的三数之和
29 0
【LeetCode-每日一题】-16. 最接近的三数之和
【LeetCode-每日一题】-16. 最接近的三数之和
|
6月前
|
Java
1657. 确定两个字符串是否接近 --力扣 --JAVA
如果可以使用以下操作从一个字符串得到另一个字符串,则认为两个字符串 接近 : 操作 1:交换任意两个 现有 字符。 例如,abcde -> aecdb 操作 2:将一个 现有 字符的每次出现转换为另一个 现有 字符,并对另一个字符执行相同的操作。 例如,aacabb -> bbcbaa(所有 a 转化为 b ,而所有的 b 转换为 a ) 你可以根据需要对任意一个字符串多次使用这两种操作。 给你两个字符串,word1 和 word2 。如果 word1 和 word2 接近 ,就返回 true ;否则,返回 false 。
31 0
|
11月前
|
存储 算法 Python
【力扣算法01】之最接近的三数之和
【力扣算法01】之最接近的三数之和
60 0
|
11月前
LeetCode: 16. 最接近的三数之和 | 双指针专题
【LeetCode: 16. 最接近的三数之和 | 双指针专题 】
39 1
|
12月前
|
测试技术 C++
力扣16-最接近的三数之和&力扣18-四数之和
力扣16-最接近的三数之和&力扣18-四数之和
60 0
|
12月前
|
算法 安全 Swift
LeetCode - #16 最接近的三数之和
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
leetcode:16.最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
44 0
力扣 -- 16. 最接近的三数之和
力扣 -- 16. 最接近的三数之和