LeetCode之16----3Sums Closest
题目:
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).
题目大意:
思路:
代码:
class Solution {
public:
    int threeSumClosest(std::vector<int>& nums, int target) {
        int result = target, dis = INT_MAX, dis_tmp, tmp;
        if (nums.size() == 0) {
            result = 0;
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.size(); ++j) {
                if (j != i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                for (int k = j + 1; k < nums.size(); ++k) {
                    if (k != j + 1 && nums[k] == nums[k - 1]) {
                        continue;
                    }
                    tmp = nums[i] + nums[j] + nums[k];
                    dis_tmp = abs(tmp - target);
                    if (dis_tmp < dis) {
                        dis = dis_tmp;
                        result = tmp;
                        if (result == target) {
                            return target;
                        }
                    }
                }
            }
        }
        return result;
    }
};
3Sums改进法:
class Solution {
public:
    int threeSumClosest(std::vector<int>& nums, int target) {
        const int n = nums.size();
        sort(nums.begin(),nums.end());
        //假设最大的三个数加起来还小于目标值,则最接近的就是这三个数相加
        if(nums[n-1] + nums[n-2] + nums[n-3] <= target)  {
            return nums[n-1] + nums[n-2] + nums[n-3];
        }
        //假设最小的三个数加起来还大于目标值,则最接近的就是这三个数相加
        if(nums[0] + nums[1] + nums[2] >= target) {
            return nums[0] + nums[1] + nums[2];
        }
        int tmp;  //候选数
        int dis = INT_MAX;  //距离
        //由于要选择三个数,所以i < n - 2
        for (int i = 0; i < n-2; i++) {
            //假设当前处理过的数字上一次处理过,则不再处理
            if (i != 0 && nums[i] == nums[i-1]) {
                continue;
            }
            //假设当前扫描的值加上最大的三个数字之后假设还小于目标值
            //说明和目标值相等的概率为零(即:差值为0的概率为0)
            if (nums[i] + nums[n-1] + nums[n-2] <= target) {
                tmp = nums[i] + nums[n-1] + nums[n-2];
                if (tmp == target) {
                    return target;
                }
                dis = tmp - target; //差值最小等于候选值减去目标值
                continue;
            }
            //假设和最大的三个数字相加之后大于目标值,说明还有希望找到差值为0的值
            //接下来就是求2Sums问题了(不同的一点是加了一个差值最小的推断)
            int target2 = target - nums[i];
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                const int sum2 = nums[j] + nums[k];
                if (abs(sum2 - target2) < abs(dis)){
                    dis = sum2 - target2;
                }
                if(sum2 > target2) {
                    k--;
                }
                else if(sum2 < target2) {
                    j++;
                }
                else {
                    return target;
                }
                while (nums[j] == nums[j-1]) {
                    j++;
                }
                while(nums[k] == nums[k+1]) {
                    k--;
                }
            }
        }
        return target + dis;
    }
};
LeetCode之16----3Sums Closest的更多相关文章
- [LeetCode][Python]16: 3Sum Closest
		
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 16: 3Sum Closesthttps://oj.leetcode.com ...
 - 《LeetBook》leetcode题解(16):3Sum Closest [M]
		
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
 - 【一天一道LeetCode】#16. 3Sum Closest
		
一天一道LeetCode系列 (一)题目: Given an array S of n integers, find three integers in S such that the sum is ...
 - 【LeetCode】16. 3Sum Closest 最接近的三数之和
		
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, three sum, 三数之和,题解,lee ...
 - 【LeetCode】16. 3Sum Closest
		
题目: Given an array S of n integers, find three integers in S such that the sum is closest to a given ...
 - LeetCode:16. 3Sum Closest(Medium)
		
1. 原题链接 https://leetcode.com/problems/3sum-closest/description/ 2. 题目要求 数组S = nums[n]包含n个整数,找出S中三个整数 ...
 - Leetcode Array 16 3Sum Closest
		
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
 - LeetCode 16. 3Sum Closest(最接近的三数之和)
		
LeetCode 16. 3Sum Closest(最接近的三数之和)
 - [LeetCode] 16. 3Sum Closest 最近三数之和
		
Given an array nums of n integers and an integer target, find three integers in nums such that the s ...
 - LeetCode 15. 3Sum 16. 3Sum Closest  18. 4Sum
		
n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...
 
随机推荐
- [luoguP2053] [SCOI2007]修车(最小费用最大流)
			
传送门 网络流的建图真的好难! 将一个点拆分成多个点的思想还需要加强. 题解 代码和题解中的图略不一样. #include <queue> #include <cstdio> ...
 - PC端有什么好用的倍速播放的软件?
			
倍速播放的目的是让自己可以以更快的速度去看视频, 加快获取信息的效率 potplay吧,和KMP是一个作者.加速播放快捷键是c,减速时x,z恢复正常.下载官网 Global Potplayer
 - Snmp的学习总结(二)
			
一.SNMP简介 SNMP指的是简单网络管理协议.它属于TCP/IP五层协议中的应用层协议.它提供了一种简单和方便的模式来管理网络中的各个元素.这里的元素就是各个被管理的对象,可以是因特网中的某个硬件 ...
 - 将list分成等数量
			
import java.util.ArrayList; import java.util.List; public class CollectionGroupUtil { public static ...
 - bzoj2850巧克力王国
			
巧克力王国 Time Limit: 60 Sec Memory Limit: 512 MBSubmit: 861 Solved: 325[Submit][Status][Discuss] Desc ...
 - request.getContextPath是为了解决相对路径的问题,可返回站点的根路径
			
假定你的web application 名称为news,你在浏览器中输入请求路径: http://localhost:8080/news/main/list.jsp 则执行下面向行代码后打印出如下结果 ...
 - Generation I
			
Generation I Oak is given N empty and non-repeatable sets which are numbered from 1 to N. Now Oak is ...
 - 【BZOJ2002】弹飞绵羊(LCT)
			
题意:给定一棵树,要求维护以下操作: 1.删除连接(x,y)的边 2.将(x,y)之间连边 3.询问某点子树大小 对于100%的数据n<=200000,m<=100000 思路:第一道有加 ...
 - zoj 3822 Domination(2014牡丹江区域赛D题)  (概率dp)
			
3799567 2014-10-14 10:13:59 Acce ...
 - android之总结(一)——原
			
1,TextView 中实现跑马灯,需求:文字左边留置一段空白,不需要紧靠在左边:设置android:padding android:padding和android:layout_margin这个地方 ...