【数据结构与算法】双指针——最接近的三数之和

最接近的三数之和

LeetCode:最接近的三数之和

题目描述:

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例:

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

思想:

时间复杂度O(n^2),外层遍历数组,内层双指针首尾相向遍历,找出最合适的三数之和。

代码:

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int twoTarget,low,high,sum=nums[0]+nums[1]+nums[2];
        for(int i=0;i<nums.length;++i){
            twoTarget = target - nums[i];
            high = nums.length-1;
            low = i+1;
            while(high>low){
                sum = Math.abs(nums[i]+nums[low]+nums[high]-target)<Math.abs(sum-target)?(nums[i]+nums[low]+nums[high]):sum;
                if(nums[low]+nums[high]<twoTarget){
                    ++low;
                }else if(nums[low]+nums[high]>twoTarget){
                    --high;
                }else{
                    return sum;
                }
            }
        }
        return sum;
    }
}

猜你喜欢

转载自www.cnblogs.com/buptleida/p/12651786.html
今日推荐