Leetcode.16 3Sum Closest

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]];
    }
}
posted @ 2020-08-17 16:28  mhp  阅读(97)  评论(0)    收藏  举报