LeetCode | 3Sum Closest(找到三个数使其和与target最接近)
2014-08-17 11:27
253 查看
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.
题目解析:
找三个数,使其和与target最近。
一开始也是按照先选一个a,然后让target-a为要找的数据,进入子函数去循环。还想着什么时候要退出,是否要遍历完i+1...n个数据。
由于数的变化性比较大,我们找到i和j的差值与target-a相近了,但i和j之间的值可能更近,也可能更远。因此要遍历完全,并且没遍历一步都要与target-a比较。
我们干脆直接维持一个和sum = a+b+c。让sum-target变小时,就更新minSum。而左右指针也是同样的走向,当sum-target>0,end--;反之,begin++。
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).
题目解析:
找三个数,使其和与target最近。
一开始也是按照先选一个a,然后让target-a为要找的数据,进入子函数去循环。还想着什么时候要退出,是否要遍历完i+1...n个数据。
由于数的变化性比较大,我们找到i和j的差值与target-a相近了,但i和j之间的值可能更近,也可能更远。因此要遍历完全,并且没遍历一步都要与target-a比较。
我们干脆直接维持一个和sum = a+b+c。让sum-target变小时,就更新minSum。而左右指针也是同样的走向,当sum-target>0,end--;反之,begin++。
class Solution { public: int threeSumClosest(vector<int> &num, int target) { if(num.size() < 3) return -1; sort(num.begin(),num.end()); int min = num[0]+num[1]+num[2]-target; for(int i = 0;i < num.size()-1;i++){ int begin = i+1; int end = num.size()-1; while(begin < end){ int sum = num[i]+num[begin]+num[end]-target; if(sum==0) return target; if(abs(sum) < abs(min)) min = sum; if(sum<0) begin++; else end--; } } return min+target; } };
相关文章推荐
- 3Sum Closest从数列中找到三个数之和最接近给定值
- leetcode-java.T016_threeSumClosest---给定包含n个整数数组S,找到S中的三个整数,从而使之和最接近给定的数,返回三个整数的总和.
- LeetCode 3Sum Closest 最接近目标数的三个数和
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- 3Sum Closest 找3个数使得和最接近的target @LeetCode
- LeetCode 16 3Sum Closest (最接近target的3个数之和)
- LeetCode 16. 3Sum Closest(最接近的和)
- LeetCode 16 3Sum Closest(最接近的3个数的和)
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- [LeetCode] 16. 3Sum Closest 最接近的三数之和 @python
- Leetcode刷题记——16. 3Sum Closest(最接近的三个数的和)
- 每天一道LeetCode-----给定序列中2/3/4个元素的和为target的所有集合,或3个元素的和最接近target的集合
- 346/5000 给定一个n个整数的数组S,在S中找到三个整数,使得总和最接近给定数量的目标。 返回三个整数的和。
- LeetCode 16. 3Sum Closest--寻找数组中的三个元素和,该和与给定的值的差最小,输出这个和(三个元素可以不连续)
- LeetCode 16. 3Sum Closest. (最接近的三数之和)
- LeetCode-142. Linked List Cycle II-using C/C++判断立案表内是否有环,有的话找到环的起始结点
- [LeetCode] 3Sum Closest
- 3Sum Closest (leetcode 16)
- 【Leetcode-Medium-494】Target Sum
- 找到的PageRank等于10的三个站点