16. 3Sum Closest

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

难度:medium

题目:

给定一整数数组和一整数,找出三个数之和最接近目标整数并返回其和。假定输入只有一个匹配的答案。

思路:先排序,固定一个数,然后剩下的数组两边夹挤。

Runtime: 10 ms, faster than 86.09% of Java online submissions for 3Sum Closest.

Memory Usage: 27 MB, less than 16.46% of Java online submissions for 3Sum Closest.

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int result = nums[0] + nums[1] + nums[2];
        int distance = Math.abs(result - target); 
        for (int i = 0; i < n - 2; i++) {
            int left = i + 1;
            int right = n - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) {
                    return target;
                }
                if (sum > target) {
                    right--;
                } else {
                    left++;
                }
                
                if (Math.abs(sum - target) < Math.abs(distance)) {
                    distance = Math.abs(sum - target);
                    result = sum;
                }
            }
        }
        
        return result;
    }
}

原文 

https://segmentfault.com/a/1190000018116543

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 16. 3Sum Closest

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址