leetcode: 3Sum Closest

159 篇文章 0 订阅

问题描述:

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

原问题链接:https://leetcode.com/problems/3sum-closest/

 

问题分析

    这个问题的思路和前面3sum的过程很接近。就是首先对数组排序,然后取target和里面取一个数的差。再到数组里去查找比较和这个差接近的值。如果相等的话就直接返回,否则记录它们的和与target值的偏差,记录下来偏差最小的那个返回。

    详细的实现代码如下:

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = 0, dif = Integer.MAX_VALUE;
        for(int i = 0; i < nums.length - 2; i++) {
            int l = i + 1, r = nums.length - 1;
            while(l < r) {
                if(nums[l] + nums[r] == target - nums[i]) return target;
                else if(nums[l] + nums[r] < target - nums[i]) {
                    if(target - nums[i] - nums[l] - nums[r] < dif) {
                        dif = target - nums[i] - nums[l] - nums[r];
                        result = nums[l] + nums[r] + nums[i];
                    }
                    l++;
                } else {
                    if(nums[l] + nums[r] + nums[i] - target < dif) {
                        dif = nums[l] + nums[r] + nums[i] - target;
                        result = nums[l] + nums[r] + nums[i];
                    }
                    r--;
                }
            }
        }
        return result;
    }
}

     总体的时间复杂度为O(N * N)。这里要注意的是实现的细节里取的索引值的范围。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值