1. 程式人生 > >leetcode16_最接近的三數之和

leetcode16_最接近的三數之和

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

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

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

 

思路:

化為twoSum問題   

public int threeSumClosest(int[] num, int target) {
		
	int res = num[0] + num[1] + num[num.length - 1];  //初始化
        Arrays.sort(num);
        for (int i = 0; i < num.length - 2; i++) {  //確定一個數
            int start = i + 1, end = num.length - 1;
            while (start < end) {
                int sum = num[i] + num[start] + num[end];
                if (sum > target) {
                    end--;
                } else {
                    start++;
                }
                if (Math.abs(sum - target) < Math.abs(res - target)) {
                    res = sum;
                }
            }
        }
        return res;
    }