LeetCode 16. 3Sum Closest

来源:互联网 发布:人工智能概念的提出 编辑:程序博客网 时间:2024/05/18 16:13

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

Subscribe to see which companies asked this question.


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

前面的题类似,变成求三个值的和最接近给定值,并返回这个和,整体思路和3sum一致,而且不需要查重简化了题目。


0 0