[leetcode note] 3Sum Closest

时间: 2019-12-13 11:54 PM
题目地址: https://leetcode.com/problems/3sum-closest/

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

给定一个由n个整数组成的数组nums和一个目标整数,请找到以nums为单位的三个整数,使总和最接近目标。 返回三个整数的和。 假设每个输入都只有一个解决方案。

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution:

public int threeSumClosest(int[] nums, int target) {
    Arrays.sort(nums);
    int len = nums.length, result = 0, gap = Integer.MAX_VALUE;
    for (int i = 0; i < len - 2; ++i) {
        int j = i + 1, k = len - 1;
        int remain = target - nums[i];
        while (j < k) {
            int sumjk = nums[j] + nums[k];
            if (sumjk == remain) {
                return target;
            }
            int gapTmp = remain - sumjk;
            gapTmp = gapTmp > 0 ? gapTmp : -gapTmp;
            if (gapTmp < gap) {
                gap = gapTmp;
                result = sumjk + nums[i];
            }
            if (sumjk < remain)  {
                ++j;
            } else {
                --k;
            }
        }
    }
    return result;
}

Runtime: 3 ms, faster than 98.67% of Java online submissions for 3Sum Closest.
Memory Usage: 36.9 MB, less than 98.33% of Java online submissions for 3Sum Closest.

欢迎关注公众号(代码如诗):
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值