LeetCode(16):3Sum Closest

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(16):3Sum Closest相关的知识,希望对你有一定的参考价值。

3Sum Closest: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).

题意:给定一个数组和目标元素,找出数组中的3个元素使其和最接近目标元素。

思路:首先对给定的数组进行排序,然后从0到数组元素长度len-2开始循环,对于每层循环,定义两个指针一个left指向i+1,right指向数组的尾部,然后开始判断i,left和start指向的元素之和是否更接近给定的元素,如果接近则更新,然后判断3个元素的和是大于给定的元素还是小于给定的元素,大于的话left指针加1,小于的话right指针减1;

代码:

public int threeSumClosest(int[] nums, int target) {
        int closest = nums[0] + nums[1] + nums[2];
        int diff = Math.abs(closest - target);
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            while (start < end) {
                int sum = nums[i] + nums[start] + nums[end];
                int newDiff = Math.abs(sum - target);
                if (newDiff < diff) {
                    diff = newDiff;
                    closest = sum;
                }
                if (sum < target)
                    start++;
                else
                    end--;
            }
        }
        return closest;
    }

以上是关于LeetCode(16):3Sum Closest的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode - 16. 3Sum Closest

Leetcode 16. 3Sum Closest

LeetCode16:3Sum Closest

leetcode 16 3Sum Closest

leetcode16 3Sum Closest

LeetCode16. 3Sum Closest