leetcode 16. 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).

解析

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int sum = nums[0] + nums[1] + nums[nums.length - 1];
        for (int i = 0; i < nums.length - 2; i++) {
            int lo = i + 1, hi = nums.length - 1;
            int tmp = target - nums[i];
            while (lo < hi) {
                int val = nums[lo] + nums[hi];
                if (Math.abs(tmp - val) <= Math.abs(sum - target)) {
                        sum = val + nums[i];
                }
                if (tmp == val) return target;
                else if (val < tmp) {
                    lo++;
                } else {
                    hi--;
                }
            }
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/lutte_/article/details/78910149
今日推荐