首页 > 学院 > 开发设计 > 正文

LeetCode-3SumClosest

2019-11-14 14:53:13
字体:
来源:转载
供稿:网友

题目:

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一样,排序之后,先确定第一个元素,然后对余下元素进行两边夹。

package sum;import java.util.Arrays;public class ThreeSumClosest {    public int threeSumClosest(int[] nums, int target) {        int len = nums.length;        Arrays.sort(nums);                int delta = nums[0] + nums[1] + nums[2] - target;        for (int i = 0; i < len - 2;) {            int l = i + 1;            int r = len - 1;            while (l < r) {                int tmp = nums[i] + nums[l] + nums[r] - target;                if (Math.abs(tmp) < Math.abs(delta))                    delta = tmp;                if (tmp == 0)                    return target;                if (tmp < 0)                    ++l;                else                    --r;            }                        do { ++i; } while (i < len && nums[i] == nums[i - 1]);        }                return target + delta;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        int[] nums = { -1, 2, 1, -4 };        int target = 1;        ThreeSumClosest t = new ThreeSumClosest();        System.out.PRintln(t.threeSumClosest(nums, target));    }}

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表