LeetCode.16 3Sum Closest

来源:互联网 发布:mac如何打拼音声调 编辑:程序博客网 时间:2024/06/07 08:26

题目:

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) {        //给定数组,和目标值,返回三个数sum最接近target的结果            //对比值        //关键一步        int result=nums[0]+nums[1]+nums[nums.length-1];        Arrays.sort(nums);                for(int i=0;i<nums.length-2;i++){            int low=i+1,high=nums.length-1;                        while(low<high){                int sum=nums[i]+nums[low]+nums[high];                if(sum==target){                    //如果相等,直接放回                    return sum;                }else if(sum>target){                    high--;                }else{                      low++;                }                                 //求最小的                if(Math.abs(sum-target)<Math.abs(result-target)){                    //存在更小的                    result=sum;                }            }        }        return result;            }}