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.

答案

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int mindiff = Integer.MAX_VALUE;
        int ans = 0;
        for(int k = 0; k < nums.length - 2; k++) {
            int i = k + 1;
            int j = nums.length - 1;
            int find = target - nums[k];
            while(i < j) {
                if(Math.abs(nums[i] + nums[j] - find) < mindiff) {
                    mindiff = Math.abs(nums[i] + nums[j] - find);
                    ans = nums[i] + nums[j] + nums[k];
                }
                else if(nums[i]+ nums[j] < find) i++;
                else j--;
            }
        }
        return ans;
    }
}

你可能感兴趣的:(3Sum Closest)