3Sum Closest
2016-05-16 14:31
330 查看
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).
描述:给定一个数组和一个目标值target。求在数组中存在3个数的和最接近target
解决思路:初始化res=nums[0]+nums[1+nums[2],而后对于每个nums[i],执行下列过程
(1)for i from 0 to nums.size()-3。每个nums[i],其实start=i+1,end=nums.size()-1,求tmp=nums[i]+nums[start]+nums[end]的和
(2)如果abs(tmp-target)<abs(res-target),则说明tmp比res更接近target,更新res。
(3)如果tmp==target,则直接返回。否则if tmp>target--->end--;else tmp<target--->start++,这样是的tmp和target更接近。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len=nums.size();
sort(nums.begin(),nums.end());//sort the nums
int res=nums[0]+nums[1]+nums[2];//init
int sum_tmp;//保存临时和
int left,right;
for(int i=0;i<len-2;i++)
{
left=i+1;
right=len-1;
while(left<right)
{
sum_tmp=nums[i]+nums[left]+nums[right];
if(abs(sum_tmp-target)<abs(res-target))
res=sum_tmp;
if(sum_tmp<target)
left++;
else if(sum_tmp>target)
right--;
else
return target;
}
}
return res;
}
};
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).
描述:给定一个数组和一个目标值target。求在数组中存在3个数的和最接近target
解决思路:初始化res=nums[0]+nums[1+nums[2],而后对于每个nums[i],执行下列过程
(1)for i from 0 to nums.size()-3。每个nums[i],其实start=i+1,end=nums.size()-1,求tmp=nums[i]+nums[start]+nums[end]的和
(2)如果abs(tmp-target)<abs(res-target),则说明tmp比res更接近target,更新res。
(3)如果tmp==target,则直接返回。否则if tmp>target--->end--;else tmp<target--->start++,这样是的tmp和target更接近。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len=nums.size();
sort(nums.begin(),nums.end());//sort the nums
int res=nums[0]+nums[1]+nums[2];//init
int sum_tmp;//保存临时和
int left,right;
for(int i=0;i<len-2;i++)
{
left=i+1;
right=len-1;
while(left<right)
{
sum_tmp=nums[i]+nums[left]+nums[right];
if(abs(sum_tmp-target)<abs(res-target))
res=sum_tmp;
if(sum_tmp<target)
left++;
else if(sum_tmp>target)
right--;
else
return target;
}
}
return res;
}
};
相关文章推荐
- 界面之下:还原真实的 MVC、MVP、MVVM 模式
- 基于JAVA的黄金数据接口调用代码实例
- 刷新Tableview的行,刷新tableview的整个区
- Shell 入门
- AndroidStudio或IDEA中连接github失败:Can't login: Connect to api.github.com:443
- cygwin编译jni项目
- jsp include文件片段
- 剑指Offer:打印1到最大的N位数
- ArcGIS 字段编辑器,编写简单python代码
- leetcode 28. Implement strStr()
- MHA手动切换 原创2 (主参与复制)
- samba安装
- EXCEL导入解析
- 怀揣爱与宽容,让自己内心更强大
- 创业沙拉北京站亲历记
- Lucene 快速入门
- Spring (3.2.4) 常用jar 包解析
- Xmanager连接 Linux 6的配置
- Storyboard学习五(简单注册页面实现)
- 01背包专题