LeetCode016-3SumClosest

3Sum Closest

Question:

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.

Example1:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

解法代码


import java.util.Arrays;

public class LeetCode16 {

    public static void main(String[] args) {
        int[] nums = new int[]{-1, 2, 1, -4};
        int rslt = new LeetCode16().threeSumClosest(nums, 1);
        System.out.println(rslt);
    }
    public int threeSumClosest(int[] nums, int target) {
        if(nums == null || nums.length == 0) {
            throw new NullPointerException("Input array is null.");
        }
        Arrays.sort(nums);
        // 表示当前三数之和到target的距离,即target减去三数之和的结果的绝对值
        int distance = Integer.MAX_VALUE;
        //表示最接近target的三数之和
        int sumClosest = 0;
        for(int i = 0; i < nums.length - 2; i++) {
            int l = i + 1,r = nums.length - 1; 
            while(l < r) {
                int curDistance = Math.abs(target - (nums[i] + nums[l] + nums[r]));
                int curSumClosest = nums[i] + nums[l] + nums[r];
                if(curSumClosest == target) {
                    return target;
                }
                if(curDistance < distance) {
                    distance = curDistance;
                    sumClosest = curSumClosest;
                }
                
                if(target < (nums[i] + nums[l] + nums[r])) {
                    r--;
                } else {
                    l++;
                }
            }
        }
        
        return sumClosest;
    }
}

Output:

2

Time And Space Complexity

Time: O(n^2) 需要两次循环遍历
Space:O(1) 不需要使用额外的存储空间

Tips

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,840评论 0 10
  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 2,351评论 0 3
  • 1. 路上偶遇一位身材高挑的美女。 爸爸:奕奕,你看那个阿姨好看吗? 奕奕(微皱眉头,一边摇头):不好看,妈妈好看...
    辛馨阅读 261评论 0 0
  • 本来挺开心的时光,被各种情绪填补替代。 时间好像时快时慢的证明着相对论的存在, 倒数着四十,默默的忍受着每一个18...
    摇曳的树阅读 264评论 0 0
  • 琪琪接了个电话,她未婚夫过来接她,她今晚要去见李煜的爷爷奶奶。至今,我们宿舍已经有两个准新娘了。 说...
    黎小语阅读 490评论 0 0

友情链接更多精彩内容