[leetcode] 16.3Sum Closest
来源:互联网 发布:图片滚动播放软件 编辑:程序博客网 时间:2024/06/10 05:48
题目:
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).
题意:
给定一个数组,一个目标值,查找其中三个数相加起来与目标值最接近的值。
思路:
采用双指针求two-sum的方法。先将数组进行排序,花费时间复杂度是O(n)。从前往后依次选取数组中元素作为三个元素中的第一个元素num[i]。然后在num[i]后面的那些元素中使用two-sum的方法查找另外两个元素。双指针一开始一个指向num[i+1],一个指向num[size-1],如果当前三个元素求得的和与target更接近,那么我们更新结果为这三个数的和。并且调整指针,如果这三个元素之和小于目标值,那么将第一个指针往后移动,代表着增大这三个数的和,否则把后面的指针往前移动。
以上。
代码如下:
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int size = num.size(); if (size < 3) return 0; else if (size == 3){ return num[0] + num[1] + num[2]; } sort(num.begin(), num.end()); int result = num[0] + num[1] + num[2]; for (int i = 0; i < size; i++) { int first = i + 1, second = size - 1; while (first < second) { int sum = num[i] + num[first] + num[second]; if (abs(sum - target) < abs(result - target)) { result = sum; if (result == target)return target; } (sum < target) ? first++ : second--; } } return result; }};
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(Java实现)
- 【leetcode】16.3Sum Closest 方法总结
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- sqlplus无法退格 (backspace)
- Java中内存泄露及垃圾回收机制
- 327 亲和串【kmp】
- Unity优化大全(三)之CPU-Physics
- 向量 规范化
- [leetcode] 16.3Sum Closest
- Android 界面滑动卡顿分析与解决方案(入门)
- Linux下Tomcat+Maven+Jenkins搭建
- 总结对Docker这个东西的想法
- 实现一个小的hover下拉列表_不算完整
- win10下环境变量设置
- Loi 2015.8.27 TEST 坑题互测
- 开源免费的C/C++网络库(c/c++ sockets library)
- android开发技巧——仿新版QQ锁屏下弹窗