【雙指針】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(n2)O(n^2)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章