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

Solution

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];       //临时值

        for (int i = 0; i < nums.length - 2; i++){          
            int j = i + 1;
            int k = nums.length - 1;
            
            while (j < k){
                int sum = nums[j] + nums[k] + nums[i];
                if (sum == target){
                    return target;
                }else if (sum > target){
                    k--;
                }else if (sum < target){
                    j++;
                }
                if (Math.abs(sum - target) < Math.abs(result - target)){
                    result = sum;                       //找最接近的加和
                }        
            }
        }
        return result;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,163评论 0 10
  • 谁让瞬间像永远,谁让未来像从前。年华似水匆匆一瞥,多少岁月轻描淡写。今天再大的事,到了明天就是小事;今年再大的事,...
    乔岩忆梦阅读 806评论 0 0
  • 拍摄地点:苏州 · 桃花坞 曾有个朋友发过桃花坞的照片,感觉不错,咨询了一番。便去呆了半天,总要相信和你审美品味差...
    三层楼阅读 3,652评论 1 2
  • 如果可以 我想站在高山之巅 只有我一个人 那么 我会不再低声细语 不再柔肠万转 我会对着苍茫群山 对着雾锁的峡谷 ...
    岷水若风阅读 1,417评论 0 0