LeetCode 16. 3Sum Closest 最接近的三数之和(Java)

题目:

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.

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

解答:

本题首先想到了与15题基本相同的思路,即先对数组进行排序后,采用双指针的解法
具体思路为:

  1. 采用 Arrays.sort() 对数组进行排序,用 res 记录目前三个数相加之和与 target 的差值,差值的绝对值越小,说明三个数总和越接近目标值
  2. 两个指针分别指向 i 的下一位和数组的尾部,计算当前三个数的差值 cur。比较当前差值 cur 和之前最小差值 res 的绝对值大小,若当前差值绝对值小,说明更接近 target,更新 res。
  3. 若差值 cur<0,说明三个数之和偏小,右移左指针;若 差值 cur>0,则说明三个数之和偏大,左移右指针
  4. 返回当前三个数最接近 target 之和,即 target-res
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = Integer.MAX_VALUE;  
        for(int i=0; i<nums.length; i++) {
            int sum = target - nums[i];
            int left = i+1;
            int right = nums.length-1;                      
            while(left<right) {
                int cur = sum - nums[left] - nums[right];
                if(Math.abs(cur) < Math.abs(res)) {
                    res = cur;
                }
                if(cur > 0) {
                    left++;
                }else{
                    right--;
                }
            }
        }
        return target-res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值