3Sum Closest(最接近的三数之和)

http://www.lintcode.com/en/problem/3sum-closest/?rand=true

    public class Solution {
        /*
         * @param numbers: Give an array numbers of n integer
         * @param target: An integer
         * @return: return the sum of the three integers, the sum closest target.
         */
        public int threeSumClosest(int[] numbers, int target) {
            // write your code here
            int diff = Integer.MAX_VALUE;
            int res = 0;
            for (int i = 0; i < numbers.length - 2; i++) {
                for (int j = i + 1; j < numbers.length - 1; j++) {
                    for (int k = j + 1; k < numbers.length; k++) {
                        int sum = numbers[i] + numbers[j] + numbers[k];
                        int abs = Math.abs(sum - target);
                        if (abs < diff) {
                            res = sum;
                            diff = abs;
                        }
                    }
                }
            }
            return res;
        }
    }

你可能感兴趣的:(3Sum Closest(最接近的三数之和))