LeetCode 16. 3Sum Closest
2016-04-12 22:44
363 查看
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.
same idea as Three Sum question: three pointers.
If use HashMap, it can be changed into Two Sum question.
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).
same idea as Three Sum question: three pointers.
If use HashMap, it can be changed into Two Sum question.
#include <vector> #include <algorithm> #include <iostream> #include <climits> using namespace std; // Suppose such a triplet must exist. // inputs may contain duplicates. int threeSumCloset(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); // nlgn time complexity. int i = 0; int closetSum; int minDiff = INT_MAX; while(i < nums.size()) { // o(n2) time complexity if(i > 0 && nums[i] == nums[i-1]) { i++; continue; } int start = i + 1; int end = nums.size() - 1; while(start < end) { if(start - 1 > i && nums[start] == nums[start - 1]) { start++; continue; } if(end + 1 < nums.size() && nums[end] == nums[end + 1]) { end--; continue; } int sum = nums[i] + nums[start] + nums[end]; if(abs(sum - target) < minDiff) { // actually once we found a 0, we can just stop and return. minDiff = abs(sum - target); closetSum = sum; } if(sum >= target) end--; else start++; } i++; } return closetSum; } int main(void) { vector<int> nums{-1, 2, 1, 4}; int res = threeSumCloset(nums, 1); cout << res << endl; }
相关文章推荐
- 【BZOJ4521】【CQOI2016】手机号码 数位DP
- J2EE中applicationContext.xml路径
- c++作业3
- activity的生命周期
- ios 如何绘制一像素
- oracle表空间加密
- android如何将生成的图片保存至手机相册并显示出来
- J2EE的13个规范
- 自定义瓷砖效果的GridView
- 青春的记忆(原创纪实小说)
- 类和对象 三角形(2)
- 微软等面试100题系列 - 41
- Java阻塞中断和LockSupport
- 程序读取Excel,单元格内容超过255被截断解决方法
- 建立,删除循环链表中的一个元素
- Js中Dom对象,控制Html元素
- Django之如何在admin页面下添加富文本编辑器
- IOS之TableViewCell重用
- 隐式转换完美解说
- java22天