LeetCoe 016 3Sum Closest

Disclaimer: This article is a blogger original article, please indicate the original blog address https://blog.csdn.net/qunqunstyle99/article/details/90770478

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

Topic analysis

This topic like 015, except that a number of target this topic is not zero but a given, and can not be equal to this target, we need to find three numbers together, and closest to the target. Only you need to return an int number like.

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int sum = -99999;//相加和
        int diff = 9999;//每次计算时的差距
        int diff1 = 9999;//最小的差距值(唯一标志)
        if (nums == null || nums.length < 3) {
            return sum;
        }
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            //check for duplicate
            if (i > 0 && nums[i] == nums[i-1]) continue;

            //set params
            int results = nums[i];
            int lb = i + 1;
            int ub = nums.length - 1;
            while (lb < ub) {
                int compliment = nums[lb] + nums[ub] + results;
                diff = Math.abs(compliment - target);
                if(diff == 0){
                //若是等于target,则是最接近的,直接返回这个值就好
                    return compliment;
                }

                else {
                    if(diff1>diff){
                    //若是距离目标变小了,则更新最小的距离和对应的相加和
                        diff1 = diff;
                        sum = compliment;
                    }

                    //这里很像上一题,但是区别是上一题target是0,若是找到一个符合的,至少改动两个元素的坐标
                    //而这里求的是最接近的,故而每次都改动一个值来进行遍历
                    if(compliment > target)ub--;//若是大于目标,则减小最大数的值
                    else lb++;//若是小于目标,则增大最小数的值

                }      
            }
        }
        return sum;
    }
}

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qunqunstyle99/article/details/90770478