Leetcode16.3Sum Closest最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
bool cmp1(int x, int y)
{
return x < y;
}
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
int len = nums.size();
sort(nums.begin(), nums.end(), cmp1);
int MIN = INT_MAX;
int res = 0;
for(int i = 0; i < len - 2; i++)
{
int low = i + 1;
int high = len - 1;
while(low < high)
{
int temp = nums[i] + nums[low] + nums[high];
if(temp == target)
{
MIN = 0;
res = target;
break;
}
else if(temp < target)
{
if(MIN > abs(target - temp))
{
MIN = abs(target - temp);
res = temp;
}
low++;
}
else
{
if(MIN > abs(target - temp))
{
MIN = abs(target - temp);
res = temp;
}
high--;
}
}
}
return res;
}
};
Leetcode16.3Sum Closest最接近的三数之和的更多相关文章
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- 【LeetCode】16. 3Sum Closest 最接近的三数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, three sum, 三数之和,题解,lee ...
- [leetcode]16. 3Sum Closest最接近的三数之和
Given an array nums of n integers and an integer target, find three integers in nums such that the s ...
- 016 3Sum Closest 最接近的三数之和
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数  br ...
- Leetcode959. Regions Cut By Slashes由斜杠划分区域
在由 1 x 1 方格组成的 N x N 网格 grid 中,每个 1 x 1 方块由 /.\ 或空格构成.这些字符会将方块划分为一些共边的区域. (请注意,反斜杠字符是转义的,因此 \ 用 &quo ...
- JZOJ100048 【NOIP2017提高A组模拟7.14】紧急撤离
题目 题目大意 给你一个01矩阵,每次询问从一个点是否可以走到另一个点. 每次走只能往右或者往下. 思考历程 这题啊,我想的时候真的是脑洞大开-- 首先,我一眼看下去,既然要询问是否联通,那么能不能求 ...
- Python-流程控制 if判断
目录 if 判断 语法 单分支结构 双分支结构 多分支结构 for循环 语法 for + break for + continue for + else range函数 for + if 练习 if ...
- [转]10 Tips for Learning a New Technology
We live in a very exciting time. Never before has education been so cheaply available to the masses ...