59.3Sum Closest-最接近的三数之和(中等题)

来源:互联网 发布:手机赚钱软件 编辑:程序博客网 时间:2024/04/29 20:49

,##

最接近的三数之和
##

  1. 题目

    给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

    注意事项
    只需要返回三元组之和,无需返回三元组本身

  2. 样例

    例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元组是 -1 + 2 + 1 = 2.

  3. 挑战

    O(n^2) 时间, O(1) 额外空间。

  4. 题解

排序后遍历,取最接近target的三个元素之和,可参见57.3Sum-三数之和(中等题)

public class Solution {    /**     * @param numbers: Give an array numbers of n integer     * @param target : An integer     * @return : return the sum of the three integers, the sum closest target.     */    public int threeSumClosest(int[] numbers ,int target) {        int n = numbers.length;        Arrays.sort(numbers);        int closet = Integer.MAX_VALUE/2;        for (int i = 0; i < numbers.length - 2; i++)         {            int left = i + 1;            int right = numbers.length - 1;            while (left < right)             {                int sum = numbers[i] + numbers[left] + numbers[right];                if (sum == target)                 {                    return sum;                }                 else if (sum < target)                 {                    left++;                }                 else                 {                    right--;                }                closet = Math.abs(sum-target) < Math.abs(closet-target)?sum:closet;            }        }        return closet;    }}

Last Update 2016.9.30

0 0
原创粉丝点击