【LeetCode16】 最接近的三數之和

  1. 最接近的三數之和
    給定一個包括 n 個整數的數組 nums 和 一個目標值 target。找出 nums 中的三個整數,使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。

例如,給定數組 nums = [-1,2,1,-4], 和 target = 1.

與 target 最接近的三個數的和爲 2. (-1 + 2 + 1 = 2).

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/3sum-closest
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解題思路

  • 和三數之和類似, 只需要利用數組有序的特性來進行雙指針移動即可

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3)
            return 0;
        
        //默認最接近是整數最大值
        int minMinus = Integer.MAX_VALUE;
        int res = 0;
        //利用雙指針,先排序
        Arrays.sort(nums);
        int h, t; 
        for(int i = 0; i < nums.length; i++) {
            h = i + 1;
            t = nums.length - 1;
            while(h < t) {
                int curNum = nums[i] + nums[h] + nums[t];
                int minus = curNum - target;
                if (minus == 0) {
                    return target;
                } else {
                    //處理差距大小
                    if (Math.abs(minus) < minMinus) {
                        minMinus = Math.abs(minus);
                        res = curNum;
                    }
                    //處理h和t指針
                    if (minus > 0) t--;
                    if (minus < 0) h++;
                }
            }
        }
        return res;
    }
}


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