描述

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. 区分replace()和replaceAll()

    replace():returns a string replacing all the old char or CharSequence to new char or CharSequence. r ...

  2. MySQL服务读取参数文件my.cnf的规律研究探索

    在MySQL中,它是按什么顺序或规律去读取my.cnf配置文件的呢?其实只要你花一点功夫,实验测试一下就能弄清楚,下面的实验环境为5.7.21 MySQL Community Server.其它版本如 ...

  3. redis笔记总结之redis数据类型及常用命令

    三.常用命令 3.1 字符串类型(string) 字符串类型是Redis中最基本的数据类型,一个字符串类型的键允许存储的数据的最大容量为512MB. 3.1.1 赋值与取值: SET key valu ...

  4. java-StringBuffer学习笔记

    字符串是敞亮,它们的值在创建之后不能更改字符串的内容一旦发生了变化,那么马上回创建一个新的对象 public class Demo1{ public static void main(String[] ...

  5. 在Simplicity Studio下创建适用于EFR32的工程项目

    1.使用平台 使用平台描述了在Simplicity Stdio下创建工程时所使用的操作系统与软件版本等. 操作系统:Windows 10 Simplcity Studio版本:Simlicity St ...

  6. for语句 2017-03-17

    一.for语句 For(初始条件:循环条件:状态改变) { 循环体 } 步骤: 1.  先判断条件 2.  如果满足条件,执行循环体 3.  状态改变 例题: 1. i++和++i 的区别: var ...

  7. JAVA的18条BASE

    关于Java的基础知识,实践证明学习OO,最终领悟“父类控制流程,子类实现具体的业务逻辑”的OO思想,需要的不是智商而是基础,也就是说,基础越好越快领悟,所以请每位S1学习Java的学员请牢记以下Ja ...

  8. python笔记之异常

    异常 內建异常在exceptions模块内,使用dir函数列出模块的内容. 自定义异常类:继承基类Exception. 异常可以使用raise语句引发,可以使用try ... except ... e ...

  9. New Windows 10 SDK - Multi-instance UWP apps

    概述 前面一篇 About Windows 10 SDK Preview Build 17110 中,我们简单介绍了 Multi-instance UWP Apps,今天结合开发过程详细讲解一下. 在 ...

  10. Java设计模式(五)Prototype原型模式

    一.场景描述 创建型模式中,从工厂方法模式,抽象工厂模式,到建造者模式,再到原型模式,我的理解是,创建对象的方式逐步从编码实现转向内存对象处理. 例如,在“仪器数据采集器”的子类/对象“PDF文件数据 ...