美文网首页leetcode
16. 3Sum Closest

16. 3Sum Closest

作者: 阿呆酱的算法工程师之路 | 来源:发表于2018-03-19 11:17 被阅读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).

思路:

关键点:利用twoSum的方法,two pointers 来辅助,每次确定第一个数字,剩下的就是找两个数字之和的问题了。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = nums[0] + nums[1] + nums[2];
        int min = Math.abs(nums[0] + nums[1] + nums[2] - target);
        for(int i = 0; i < nums.length - 2; i++) {
            int sum = target - nums[i];
            int j = i + 1;
            int k = nums.length - 1;
            int del = -1;
            while(j < k) {
                int tp = nums[j] + nums[k];
                del = Math.abs(sum - tp);
                if(del < min) {
                    min = del;
                    res = nums[i] + nums[j] + nums[k];
                }
                if(tp == sum) {
                    return target;
                } else if(tp < sum) {
                    j++;
                } else {
                    k--;
                }
            }
        }
        return res;
    }
} 

相关文章

  • LeetCode #16 2018-07-28

    16. 3Sum Closest Given an array nums of n integers and an...

  • Day3

    16. 3Sum Closest Given an array S of n integers, find thr...

  • LeetCode 16. 3Sum Closest

    16. 3Sum Closest Given an array S of n integers, find thr...

  • 16. 3Sum Closest

    题目: Given an array S of n integers, find three integers i...

  • 16. 3Sum Closest

    题目: 给定一个nums由n个整数和一个整数组成的数组target,找出三个整数nums,使总和最接近target...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    先排序,然后左右夹逼,每次当sum-target < diff 用diff记录下最小距离

网友评论

    本文标题:16. 3Sum Closest

    本文链接:https://www.haomeiwen.com/subject/yrmuqftx.html