leetcode: 16. 3Sum Closest

Difficulty

Medium

Description

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

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution

Time Complexity: O(n^2)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        int ret = 0;
        for (int i = 0; i + 2 < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int j = i + 1;
            int k = nums.length - 1;
            int sum = target - nums[i];
            while (j < k) {
                int dif = nums[j] + nums[k] - sum;
                if (dif == 0)
                    return target;
                else if (dif > 0) k--;
                else j++;
                if (min > Math.abs(dif)) {
                    min = Math.abs(dif);
                    ret = target + dif;
                }          
            }
        }
        return ret;         
    }
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/86262892