3Sum Closest 找出最接近目标的三元组

来源:互联网 发布:activiti5源码下载 编辑:程序博客网 时间:2024/05/16 08:30

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).

这还是3Sum 问题,之前,我们是要找 = 目标的三元组。现在是接近。

即我们的 “  a + b + c - target ” 是所有数组中的三元组中最小的。

我们在原来的3Sum上进行改动,额外增加两个变量minDif :用来标记当前最小的差距;

和 value变量,用来标记当前的形成最小差距的 a + b + c 的值 (即需要的返回值)。

复杂度:

时间复杂度:O(n^2 )

空间复杂度:O ( 1 )

效率:

代码:

    public int threeSumClosest(int[] nums, int target) {        Arrays.sort(nums);        int minDif = Integer.MAX_VALUE;        int value = 0;        for (int i = 0; i < nums.length; i++) {            if (i > 0 && nums[i] == nums[i - 1]) {                continue;            }            int lo = i + 1;            int hi = nums.length - 1;            while (lo < hi) {                int curVal = nums[i] + nums[lo] + nums[hi];                if (Math.abs(curVal - target) < minDif) {                    minDif = Math.abs(curVal - target);                    value = curVal;                }                if (curVal == target) {                    return value;                } else if (curVal > target) {                    hi--;                } else {                    lo++;                }            }        }        return value;    }


1 0
原创粉丝点击