leetcode-16-最接近的三数之和(java)


title: leetcode-16-最接近的三数之和
date: 2019-09-04 20:34:07
categories:

  • leetcode
    tags:
  • leetcode

16-最接近的三数之和

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum-closest
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 解法:在上一篇的基础上修改一下即可

    class Solution {
    public int threeSumClosest(int[] nums, int target) {
            if (nums.length<3)
                return 0;
            Arrays.sort(nums);
            int absMinLen = Integer.MAX_VALUE;
            int a=0;
            for (int i=0;i<nums.length-2;i++){
                if(i>0&&nums[i]==nums[i-1])
                    continue;
                int left = i+1;
                int right = nums.length-1;
                while (left<right){
                    a = nums[i]+nums[left]+nums[right]-target;
                    if(Math.abs(a)<Math.abs(absMinLen)){
                        absMinLen = a;
    
                    }
                    if (a>0){
                        right--;
                    }else{
                        left++;
                    }
                }
            }
            return  target+absMinLen;
    }
    }
    

你可能感兴趣的:(学生,java,数据结构)