16. 3Sum Closest
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).
题意:
给一个含有n个整数的S数组,查找在S中的三元组,使三个数字的和最靠近目标值 ,返回最接近目标值的三个整数的和。假设每个输入都已一个确切的答案。
思路:
思想大致都和15. 3Sum相同,先排序,然后利用三个指针,一个指针指向固定元素,另外两个做为这个固定元素后面的两个移动指针,然后三元素求和,当和大于目标值的时候说明所求和大,需减小,所以把尾指针前移,小于目标值的时候说明所求和小,需增大,所以把首指针后移
1 | class Solution { |
Java Code:
1 | class Solution { |