题目

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).

分析

这题目与上一题十分相似。求出整数数组序列中与目标值最接近的三元组元素之和。

解这个题目条件反射的方法是三层遍历,求和比较,但是显而易见,在LeetCode提交时必然会出现超时的异常。所以必须另觅他法,这个题目的AC代码源于参考,在此表示感谢。

Time Limit Exceeded代码

class Solution {
public: //方法一:三层穷举,超时异常
int threeSumClosest(vector<int>& nums, int target) { int len = nums.size();
if (len < 3)
{
return 0;
}
int closest = nums[0] + nums[1] + nums[2]; for (int i = 1; i < len-2; i++)
{
//首先进行去重操作
if (nums[i] == nums[i - 1])
continue; for (int j = i + 1; j < len - 1; j++)
{
if (nums[j] == nums[j - 1])
continue;
for (int k = j + 1; k < len; k++)
{
if (nums[k] == nums[k - 1])
continue;
int sum = nums[i] + nums[j] + nums[k]; if (sum == target)
{
closest = sum;
break;
}//if
else if (abs(sum - target) < abs(closest - target))
{
closest = sum;
}//elif
else
continue;
}//for
}//for
}//for return closest;
}
int abs(int a)
{
return a > 0 ? a : 0-a;
}
};

AC代码

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
size_t size = nums.size();
if (size < 3)
{
cout << "num size must bigger than there!" << endl;
return 0;
}
sort(nums.begin(), nums.end()); // 对于以下的处理过程必须事先排序,类似二分搜索
int result = 0; // 记录最终结果
int distance = numeric_limits<int>::max(); // signed int
int sum = 0; // 中间结果
size_t i = 0, j = i + 1, k = size - 1; for (i = 0; i < size - 2; i++) // 三元组的第一个元素一次遍历,范围为[0...n-3]
{
// 去重避免重复计算,如果和上次同则跳过
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
} j = i + 1; // 选定三元组第一个元素后,第二个元素从第一个元素的下一个位置开始考察
k = size - 1; // 选定三元组第一个元素后,第三个元素从数组末尾开始考察
while (j < k) // 三元组的后两个元素利用左右逼近来跳过效率,选定第一个元素后,其后的所有元素只需考察一遍
{
sum = nums[i] + nums[j] + nums[k];
if (sum == target) // 存在距离最近为0则直接返回,否则穷举选取非0最小距离
{
return sum;
}
else if (sum < target)
{
if ((target - sum) < distance)
{
result = sum;
distance = target - sum;
}
j = j + 1;
// 避免重复计算,如果和上次同则跳过
if (nums[j] == nums[j - 1])
{
j = j + 1;
}
}
else if (sum > target)
{
if ((sum - target) < distance)
{
result = sum;
distance = sum - target;
}
k = k - 1;
// 避免重复计算如果和上次同则跳过
if (nums[k] == nums[k + 1])
{
k = k - 1;
} }
}
}
return result;
}
};

GitHub测试程序源码

LeetCode(16)3Sum Closest的更多相关文章

  1. leetcode第16题--3Sum Closest

    Problem:Given an array S of n integers, find three integers in S such that the sum is closest to a g ...

  2. LeetCode(16):最接近的三数之和

    Medium! 题目描述: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只 ...

  3. LeetCode(15) 3Sum

    题目 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...

  4. LeetCode(15)3Sum

    题目如下: Python代码: def threeSum(self, nums): res = [] nums.sort() for i in xrange(len(nums)-2): if i &g ...

  5. Web 在线文件管理器学习笔记与总结(15)剪切文件夹 (16)删除文件夹

    (15)剪切文件夹 ① 通过rename($oldname,$newname) 函数实现剪切文件夹的操作 ② 需要检测目标文件夹是否存在,如果存在还要检测目标目录中是否存在同名文件夹,如果不存在则剪切 ...

  6. Windows Phone开发(16):样式和控件模板

    原文:Windows Phone开发(16):样式和控件模板 在前面资源一文中也提过样式,样式就如同我们做HTML页排版时常用到的CSS样式表,它是对于特定娄型的可视化元素,应该可以直接说是针对控件的 ...

  7. Java设计模式(16)中介模式(Mediator模式)

    Mediator定义:用一个中介对象来封装一系列关于对象交互行为. 为何使用Mediator模式/中介模式 各个对象之间的交互操作非常多,每个对象的行为操作都依赖彼此对方,修改一个对象的行为,同时会涉 ...

  8. leecode刷题(16)-- 字符串转换整数

    leecode刷题(16)-- 字符串转换整数 字符串转换整数 描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格 ...

  9. Qt 学习之路 2(16):深入 Qt5 信号槽新语法

    Qt 学习之路 2(16):深入 Qt5 信号槽新语法  豆子  2012年9月19日  Qt 学习之路 2  53条评论 在前面的章节(信号槽和自定义信号槽)中,我们详细介绍了有关 Qt 5 的信号 ...

随机推荐

  1. hud3371 Connect the Cities 简单最小生成树

    //我看过Discuss说不能用克鲁斯卡尔因为有很多边 //但是只能用G++过,C++的确超时 #include <stdio.h> #include <string.h> # ...

  2. Codeforces Round #402 (Div. 2) B

    Description Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. ...

  3. 数组Reduce的应用

    数组Reduce的应用 参考 简单应用 var arr = [1,2,3,4,5] var sum = arr.reduce(function (prev, cur, index, arr) { co ...

  4. Vue项目搭建流程 以及 目录结构构建

    Vue项目搭建流程 以及 目录结构构建 一个小的Vue项目, 基于微信浏览器的移动端, 做了这么多的练习项目, 这一次准备记录下构建的过程, 以方便以后的调高效率 环境准备 操作系统 我的 windo ...

  5. Spring------自动化装配Bean(三)

    上一篇是基于java手动装配bean的实现,这一篇将通过xml手动装配bean来实现. xml配置相对于java配置有点: xml配置更加快捷 但不宜扩展 一.打开application.xml 1. ...

  6. Java提供的序列化和反序列化

    序列化:是指将Java对象转换为二进制数据. 反序列化:将二进制数据转换为Java对象. 与序列化功能相关的类有: java.io.Serializable; java.io.ObjectOutput ...

  7. 猩球StarBall ,一个方便约球的小程序

    扫描小程序码直接进入小程序 猩球StarBall 是一款为热爱运动的人群提供便利的小程序. 开发技术为Java +Mysql 其中用到的技术框架为SpringBoot,Mybatis,Redis,Qu ...

  8. springboot项目启动问题

    在调试项目的时候有遇到这样一个问题: 项目启动后访问不通,编译没有任何问题,启动也没有报错,日志在打,但是访问不通.而且之前一直可以正常访问,在没改任何代码的情况下不能访问了. 尝试很多次偶然发现,点 ...

  9. js事件、Js中的for循环和事件的关系、this

    一.js事件  1.事件 用户在网页中所触发的行为 鼠标滑动种类很多,键盘.表单特列: 点击:onclick 鼠标进入:onmouseenter 鼠标离开:onmouseleave 鼠标悬浮:onmo ...

  10. VCS filelist 文件格式

    VCS在运行仿真一般都会加仿真参数 –f filelist,filelist 是包含其他的仿真参数和整个工程的文件列表.具体格式如下: //file list format, just for exa ...