1. 程式人生 > >【組合&元素和】3Sum Closest

【組合&元素和】3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
題意:求離給定值最近的三元素和

解法:先固定一個值轉化成二元素和問題

public class Solution {
    
    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int len = num.length;
        int a = Integer.MAX_VALUE;
        int b = 0;
        
        for(int i=0; i<len; i++){
            int p = i+1, q = len-1;
            while(p < q){
                int t = num[i] + num[p] + num[q];
                if(t == target) return t;
                
                int ta = Math.abs(t - target);
                if(ta < a){
                    a = ta;
                    b = t;
                }
                
                if(t < target)
                    p++;
                else q--;
            }   
        }
        return b;
    }
}