题外话

鉴于这一题的核心思路和leetcode15的思路相同,可以先写一下15题并参考一下我之前的一篇博客

题目要求

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

翻译过来就是,假设一个有n的元素的整数数组S,从S中找到三个值,这三个值的距离输入的目标值最近。返回这三个值的和。

思路一:三指针

这里的思路和leetcode15是一样的,就是用三个指针获得三个值并计算他们的和。不同的是和当前的最小距离比较,代码如下

public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int length = nums.length;
        int closest = nums[0]+nums[1]+nums[2] - target;
        for(int i = 0 ; i<length-2 ; ){
            for(int j = i+1, k = length-1 ; j<k ; ){
                int value = nums[i] + nums[j] + nums[k] - target;
                if(value<0){
                    while(nums[j]==nums[++j] && j < k);
                }
                if(value>0){
                    while(nums[k--] == nums[k] && j < k);
                }
                if(value==0){
                    return target;
                }
                if(Math.abs(value) < Math.abs(closest)){
                    closest = value;
                }        
            }
            while(nums[i] == nums[++i] && i < nums.length - 2);
        }
            
        return closest + target;
    }

思路二:hashmap等

同leetcode15,请直接参考我的博客

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行