首页 > 其他 > 详细

Leetcode.16 3Sum Closest

时间:2020-08-17 17:23:01      阅读:70      评论:0      收藏:0      [点我收藏+]

Leetcode.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 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Constraints:

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4

Solution

双指针

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int[] res = new int[3];
        int dis = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            int j = i+1;
            int l = nums.length-1;
            int t = target - nums[i];
            while(j<l){
                //需要先判断,如果后判断将存在j==l的情况,此时不满足循环不变量
                if(Math.abs(nums[j]+nums[l]-t)<dis){
                    res[0] = i;
                    res[1] = j;
                    res[2] = l;
                    dis = Math.abs(nums[j]+nums[l]-t);
                }
                //判断完两边指针再走
                if(nums[j] + nums[l] == t){
                    return nums[i]+nums[j]+nums[l];
                }else if(nums[j]+nums[l]<t){
                    j++;
                }else{
                    l--;
                }
            
            }
        
        }
        return nums[res[0]] + nums[res[1]] + nums[res[2]];
    }
}

Leetcode.16 3Sum Closest

原文:https://www.cnblogs.com/xm08030623/p/13518403.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!