题目

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.

  1. For example, given array S = {-1 2 1 -4}, and target = 1.
  2. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

分析

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

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

Time Limit Exceeded代码

  1. class Solution {
  2. public:
  3. //方法一:三层穷举,超时异常
  4. int threeSumClosest(vector<int>& nums, int target) {
  5. int len = nums.size();
  6. if (len < 3)
  7. {
  8. return 0;
  9. }
  10. int closest = nums[0] + nums[1] + nums[2];
  11. for (int i = 1; i < len-2; i++)
  12. {
  13. //首先进行去重操作
  14. if (nums[i] == nums[i - 1])
  15. continue;
  16. for (int j = i + 1; j < len - 1; j++)
  17. {
  18. if (nums[j] == nums[j - 1])
  19. continue;
  20. for (int k = j + 1; k < len; k++)
  21. {
  22. if (nums[k] == nums[k - 1])
  23. continue;
  24. int sum = nums[i] + nums[j] + nums[k];
  25. if (sum == target)
  26. {
  27. closest = sum;
  28. break;
  29. }//if
  30. else if (abs(sum - target) < abs(closest - target))
  31. {
  32. closest = sum;
  33. }//elif
  34. else
  35. continue;
  36. }//for
  37. }//for
  38. }//for
  39. return closest;
  40. }
  41. int abs(int a)
  42. {
  43. return a > 0 ? a : 0-a;
  44. }
  45. };

AC代码

  1. class Solution {
  2. public:
  3. int threeSumClosest(vector<int>& nums, int target) {
  4. size_t size = nums.size();
  5. if (size < 3)
  6. {
  7. cout << "num size must bigger than there!" << endl;
  8. return 0;
  9. }
  10. sort(nums.begin(), nums.end()); // 对于以下的处理过程必须事先排序,类似二分搜索
  11. int result = 0; // 记录最终结果
  12. int distance = numeric_limits<int>::max(); // signed int
  13. int sum = 0; // 中间结果
  14. size_t i = 0, j = i + 1, k = size - 1;
  15. for (i = 0; i < size - 2; i++) // 三元组的第一个元素一次遍历,范围为[0...n-3]
  16. {
  17. // 去重避免重复计算,如果和上次同则跳过
  18. if (i > 0 && nums[i] == nums[i - 1])
  19. {
  20. continue;
  21. }
  22. j = i + 1; // 选定三元组第一个元素后,第二个元素从第一个元素的下一个位置开始考察
  23. k = size - 1; // 选定三元组第一个元素后,第三个元素从数组末尾开始考察
  24. while (j < k) // 三元组的后两个元素利用左右逼近来跳过效率,选定第一个元素后,其后的所有元素只需考察一遍
  25. {
  26. sum = nums[i] + nums[j] + nums[k];
  27. if (sum == target) // 存在距离最近为0则直接返回,否则穷举选取非0最小距离
  28. {
  29. return sum;
  30. }
  31. else if (sum < target)
  32. {
  33. if ((target - sum) < distance)
  34. {
  35. result = sum;
  36. distance = target - sum;
  37. }
  38. j = j + 1;
  39. // 避免重复计算,如果和上次同则跳过
  40. if (nums[j] == nums[j - 1])
  41. {
  42. j = j + 1;
  43. }
  44. }
  45. else if (sum > target)
  46. {
  47. if ((sum - target) < distance)
  48. {
  49. result = sum;
  50. distance = sum - target;
  51. }
  52. k = k - 1;
  53. // 避免重复计算如果和上次同则跳过
  54. if (nums[k] == nums[k + 1])
  55. {
  56. k = k - 1;
  57. }
  58. }
  59. }
  60. }
  61. return result;
  62. }
  63. };

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. PHP数组直接相加和array_merge的区别

    array_merge是很常用的数组合并函数,但是两个数组直接相加对开发也是很有帮助的,两者之间有什么差别,这里记录一下: 首先是以数字为索引 array_merge会将两个数组按照先后顺序组成一个新 ...

  2. USB转串口 FT232/PL2303芯片使用体会

    现在笔记本上很少带有串口了,而串口又是做电子设计必备的通讯接口之一,好在USB转串口比较方便,市面上常用的USB转串口芯片有很多,最常见的有FT232.PL2303.CH340三种 原理:单片机的TX ...

  3. SpringMVC + ajax

    1.ajax 返回汉字乱码 解决方法: http://blog.sina.com.cn/s/blog_5f39177b0101it7h.html //方案一 response.setCharacter ...

  4. P1851 好朋友

    题目背景 小可可和所有其他同学的手腕上都戴有一个射频识别序列号码牌,这样老师就可以方便的计算出他们的人数.很多同学都有一个“好朋友” .如果 A 的序列号的约数之和恰好等于B 的序列号,那么 A的好朋 ...

  5. C#中分部类和分部方法的应用

    本篇文章介绍了,C#中分部类和分部方法的应用.需要的朋友参考下     分部类(Partial Class)在C#2.0引入,分部方法(Partial Method)在C#3.0引入,这两个语法特性都 ...

  6. centos安装字体

    cd /usr/local/fonts/zh_CN/TrueType/ cp /root/simsunb.ttf /usr/share/fonts/zh_CN/TrueType/ mkfontscal ...

  7. Oracle创建用户及权限设置

    oracle用户创建及权限设置 权限: create session create table unlimited tablespace connect resource dba 例: #sqlplu ...

  8. Ubuntu14.04 LTS安装 OpenCV-3.0.0-rc1 + QT5.4.1

    I 安装配置工作前的准备 2 II 安装 OpenCV 2 III 安装QT 3 IV 使QT能够使用OpenCV 3 如果顺利,整个过程应该3个小时左右能够完成. 我整个过程用了一早上,配置过程中有 ...

  9. C# 获取本机IP(优化项目实际使用版)

    好一段时间没来更新博客了,因为密码实在记不住,烦死了,密码干脆直接用那个找回密码链接的一部分. 吐槽完说正事了,关于C#  获取本机IP的,最开始用的是下面的,但是因为获取IP的有点多,而且难判断,忽 ...

  10. Android-Emulator使用

    1.查看当前android支持的avd版本 2.创建Emulator avd: android create avd -n magicyu -t 2 -n后面接需要创建avd的名字,-t后面接需要创建 ...