【LeetCode】 111 最接近的三數之和

題目:

image-20210201021256809

image-20210201021241078

解題思路:

for加上雙指針

https://leetcode-cn.com/problems/3sum-closest/solution/zui-jie-jin-de-san-shu-zhi-he-by-leetcode-solution/

代碼:

import java.util.Arrays;

public class LC133 {

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int best = 10000000;

        // 枚舉 a
        for (int i = 0; i < n; ++i) {
            // 保證和上一次枚舉的元素不相等
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            // 使用雙指針枚舉 b 和 c
            int j = i + 1, k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                // 如果和爲 target 直接返回答案
                if (sum == target) {
                    return target;
                }
                // 根據差值的絕對值來更新答案
                if (Math.abs(sum - target) < Math.abs(best - target)) {
                    best = sum;
                }
                if (sum > target) {
                    // 如果和大於 target,移動 c 對應的指針
                    int k0 = k - 1;
                    // 移動到下一個不相等的元素
                    while (j < k0 && nums[k0] == nums[k]) {
                        --k0;
                    }
                    k = k0;
                } else {
                    // 如果和小於 target,移動 b 對應的指針
                    int j0 = j + 1;
                    // 移動到下一個不相等的元素
                    while (j0 < k && nums[j0] == nums[j]) {
                        ++j0;
                    }
                    j = j0;
                }
            }
        }
        return best;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{2,4,6,-4,1};
        LC133 lc133 = new LC133();
        int i = lc133.threeSumClosest(arr, 4);
        System.out.println(i);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章