16. 3Sum Closest

Description

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

Solution

Three-pointers, O(n^2) time

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int res = nums[0] + nums[1] + nums[2];  // important, don't set to MAX_VALUE
        Arrays.sort(nums);
        int i = 0;
        int n = nums.length;
        
        while (i < n) {
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                
                if (sum < target) {
                    ++j;
                } else if (sum > target) {
                    --k;
                } else {
                    return sum;
                }
                
                if (Math.abs(sum - target) < Math.abs(res - target)) {
                    res = sum;
                }
            }
            ++i;
        }
        
        return res;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,151评论 0 10
  • 丁酉年,八月初八 客居西子湖畔,有感,故作此文。无他,以手记心而已。 涛涛江水,亘古流长。 不知岁月,不惜奔狂。 ...
    沥风沐雨阅读 3,081评论 0 0
  • 每年都会陷入这样的时期无力 愤懑 困扰 不爱自己 也问自己原因是什么 是不上进?不自知?不妥协? 觉得自己像是一个...
    想过美丽人生阅读 1,586评论 0 1
  • 人们一段时间的分离再重聚,会进入一个蜜月期,男女朋友如此,夫妻如此,我和珍珠也一样。但即使在蜜月期,我也不能无视她...
    3y三一阅读 1,358评论 0 0
  • 【日更145】 虽然截至目前我已经持续“日更”了140多天,并且眼下还是会把这个计划持续下去,但仍然会在许多时候感...
    唐斩2086阅读 2,454评论 2 3