LeetCode 16. 3Sum Closest
来源:互联网 发布:1050ti 知乎 编辑:程序博客网 时间:2024/05/16 01:22
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).
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;}
0 0
- LeetCode 16. 3Sum Closest
- LeetCode --- 16. 3Sum Closest
- [Leetcode] 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- [leetcode] 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- LeetCode - 16. 3Sum Closest
- [LeetCode]16. 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode *** 16. 3Sum Closest
- Leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【LeetCode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 青春的记忆(原创纪实小说)
- 自定义瓷砖效果的GridView
- Django REST framework教程三: 基于类的视图
- ios 如何绘制一像素
- Android减少布局层次--有关Activity根视图DecorView的思考
- LeetCode 16. 3Sum Closest
- J2EE中applicationContext.xml路径
- LongWayToGo
- 【BZOJ4521】【CQOI2016】手机号码 数位DP
- 分享8年开发经验,浅谈java程序员职业规划
- virtio的vring队列
- linux -- Fedora安装TFTP服务器
- large scale image retrieval --- using the cnn codes as feature
- CollapsingToolbarLayout的使用