描述

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.

示例

Given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

算法分析

难度:中

分析:给定整型数组中和一个指定的目标整型值,从数组中找到3个元素,满足3个元素之和最接近目标值,返回结果为3个元素之和。

思路:大体思路类似3Sum算法,也是先将数组排序,然后开始遍历,3个元素分别是当前遍历的元素、夹逼开始元素默认当前元素后面的元素,夹逼结束元素默认数组最后的元素,通过夹逼开始元素递增和夹逼结束元素递减来实现夹逼:

 1. 如果这3个元素之和比目标值大,则需要夹逼结束元素值变小,才有可能接近目标值,所以夹逼结束元素递减;

 2. 如果这3个元素之和不比目标值大,则需要夹逼开始元素值变大,才有可能接近目标值,所以夹逼开始元素递增;

本次遍历结束后,再判断本次3元素之和目前记录的最接近之和比较,取更接近的做为返回结果,然后继续遍历,直至遍历结果,获得返回结果。

代码示例(C#)

public int ThreeSumClosest(int[] nums, int target)
{
int res = nums[0] + nums[1] + nums[nums.Length - 1]; //排序后遍历
Array.Sort(nums);
for (int i = 0; i < nums.Length - 2; i++)
{
//从当前后面的元素和最后一个元素,两边夹逼
int lo = i + 1, hi = nums.Length - 1;
while (lo < hi)
{
int sum = nums[i] + nums[lo] + nums[hi];
if (sum > target)
{
hi--;
}
else
{
lo++;
}
//如果此次遍历的3个元素的和更接近,则赋值返回的结果
if (Math.Abs(sum - target) < Math.Abs(res - target))
{
res = sum;
}
}
}
return res;
}

复杂度

  • 时间复杂度O (n²).
  • 空间复杂度O (1).

附录

算法题丨3Sum Closest的更多相关文章

  1. 算法题丨3Sum

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

  2. 算法题丨Two Sum

    描述 Given an array of integers, return indices of the two numbers such that they add up to a specific ...

  3. 算法题丨4Sum

    描述 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...

  4. 算法题丨Remove Duplicates from Sorted Array II

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 示例 Giv ...

  5. 算法题丨Longest Consecutive Sequence

    描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence ...

  6. 算法题丨Remove Element

    描述 Given an array and a value, remove all instances of that value in-place and return the new length ...

  7. 算法题丨Move Zeroes

    描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the rela ...

  8. 算法题丨Next Permutation

    描述 Implement next permutation, which rearranges numbers into the lexicographically next greater perm ...

  9. 算法题丨Remove Duplicates from Sorted Array

    描述 Given a sorted array, remove the duplicates in-place such that each element appear only once and ...

随机推荐

  1. js文本框字符数输入限制

    我们常常在前台页面做一些文本输入长度的验证,为什么呢?因为数据库字段设置了大小,如果不限制输入长度,那么写入库时就会引发字符串截断异常.今天就给大家分享一个jquery插件来解决这一问题. (func ...

  2. 大三小学期 Android开发的一些经验

    1.同一个TextView几种颜色的设置: build=(TextView)findViewById(R.id.building); SpannableStringBuilder style = ne ...

  3. java 开发 face++ 人脸特征识别系统

    首先要在 face++ 注册一个账号,并且创建一个应用,拿到 api key 和 api secret: 下载 java 接入工具,一个 jar 包:https://github.com/FacePl ...

  4. MySQL多数据源笔记3-分库分表理论和各种中间件

    一.使用中间件的好处 使用中间件对于主读写分离新增一个从数据库节点来说,可以不用修改代码,达到新增节点数据库而不影响到代码的修改.因为如果不用中间件,那么在代码中自己是先读写分离,如果新增节点, 你进 ...

  5. 基于etcd的Rabbitmq队列订阅负载均衡

    go-qb Load balancer for rabbitmq queue subscribing Feature Rabbitmq queue subscription load balancin ...

  6. EasyUI 二次加载toolbar异常问题解决

    问题:easyUI初次渲染正常,之后会出问题,toolbar重复加载 解决办法:每次加载之前先从body中删除已经渲染的工具栏-->重新加载-->手动渲染工具栏 代码: function ...

  7. 使用Angular CLI进行单元测试和E2E测试

    第一篇文章是: "使用angular cli生成angular5项目" : http://www.cnblogs.com/cgzl/p/8594571.html 第二篇文章是: & ...

  8. SAP OLE中常用的一些方法和属性

    1.ole中如何保存和退出. call method of sheetname = filepath # =. call method of applicationname 'quit'. 2.给sh ...

  9. Unity的常用API

    1.Event Function:事件函数   Reset() :被附加脚本时.在游戏物体的组件上按Reset时会触发该事件函数 Start() :在游戏初始化时会执行一次 Update() :每一帧 ...

  10. Flask入门HelloWorld

    Flask入门HelloWorld Flask官网:http://flask.pocoo.org/ Flask中文翻译:http://dormousehole.readthedocs.io/en/la ...