[LeetCode] 16 - 3Sum Closest
2015-08-29 14:37
357 查看
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.
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int size = nums.size();
if (size < 3) {
return 0;
}
int sum = 0;
unsigned int diff = 0xffffffff;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < size - 2; ++i) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
int j = i + 1;
int k = size - 1;
for (; j < k; ) {
int tmp = nums[i] + nums[j] + nums[k];
int tmp0 = (tmp - target);
if (tmp0 == 0) { return tmp; }
if (abs(tmp0) < diff) {
diff = abs(tmp0);
sum = tmp;
}
if (tmp0 > 0) {
--k;
} else {
++j;
}
}
}
return sum;
}
};
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(vector<int>& nums, int target) {
int size = nums.size();
if (size < 3) {
return 0;
}
int sum = 0;
unsigned int diff = 0xffffffff;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < size - 2; ++i) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
int j = i + 1;
int k = size - 1;
for (; j < k; ) {
int tmp = nums[i] + nums[j] + nums[k];
int tmp0 = (tmp - target);
if (tmp0 == 0) { return tmp; }
if (abs(tmp0) < diff) {
diff = abs(tmp0);
sum = tmp;
}
if (tmp0 > 0) {
--k;
} else {
++j;
}
}
}
return sum;
}
};
相关文章推荐
- linux系统中重置mysql的root密码
- ioctl()函数详解
- libxml/tree.h file not found
- Servlet 与 JSP 核心编程
- UI 15 NetWorkingTool 封装JSON解析
- Http请求中Content-Type讲解以及在Spring MVC中的应用
- 《剑指Offer》:删除在另一个字符串中出现的字符
- 基于Apache POI 从xlsx读出数据
- 基于Apache POI 从xlsx读出数据
- C语言基础(xcode)
- fix pycurl link error
- CentOS系统下的Hadoop集群(第10期)_MySQL关系数据库
- JavaScript学习笔记2-附录(JavaScript中的内置对象)
- 解决CentOS 6.5中,Python-2.7.*交互模式下方向键、退格键等出现乱码的问题
- 幻数
- jquery 鼠标 滑轮 滚动 方向
- noip2003 神经网络 (拓扑排序,深搜)
- leetcode Implement Trie (Prefix Tree)
- Activity间数据传递与版本兼容问题
- 第二讲实例变量可见度,set/get方法,自定义初始化(代码) 及description的使用