【双指针】B020_LC_最接近的三数之和(二分思想 + 剪枝)

一、Problem

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.

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

方法一:双指针

暴力法即三层循环枚举三个数,不难。

双指针的做法就是固定一个端点,然后在一段区间中循环其他两个数,检查和 target 的绝对值差的大小

剪枝:这里如果有重复元素,排序之后会变成相邻,而对重复的元素再求一起最接近的和是没有必要的,所以可以提前剪枝

class Solution {
    public int threeSumClosest(int[] a, int tar) {
        Arrays.sort(a);
        int n = a.length, ans = a[0] + a[1] + a[2];

        for (int i = 0; i < n; i++) {
        	if (i > 0 && a[i-1] == a[i])
                continue;
            int l = i+1, r = n-1;
            while (l < r) {
                int cur = a[i] + a[l] + a[r];
                if (Math.abs(cur-tar) < Math.abs(ans-tar))
                    ans = cur;
                if (cur > tar)
                    r--;
                else if (cur < tar)
                    l++;
                else 
                    return ans;
            }
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2)
  • 空间复杂度: O ( 1 ) O(1)

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/106941501
今日推荐