美文网首页LeetCode
LeetCode-array-3Sum Closest

LeetCode-array-3Sum Closest

作者: 萤火之森ss | 来源:发表于2017-07-05 14:03 被阅读7次

题目:
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).

给一个数组,一个值,数组中的三个元素的合和值最相近,返回合;

代码基本和上一篇一样的思路

package LeetCode1;

import java.util.Arrays;

/**
 * Created by Wangjianxin on 2017/7/5 0005.
 */
public class ThreeSumColsest {


    public static void main(String[] args) {
        int [] s = {1,1,1,0};
        int t = 100;
        System.out.println(threeSumClosest(s,t));
    }


    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int compare = Integer.MAX_VALUE;
        int nsum = 0;
        for(int i =0;i <len ;i++){

            int start = i;
            int left = i +1;
            int right = len - 1;

            while (left < right){
                int sum = nums[start] + nums[left] + nums[right];
                int dif = Math.abs(sum -target);

                if(sum == target){
                    return sum;
                }
                if(sum > target){
                    right --;
                }
                if(sum < target){
                    left++;
                }
                if(compare >= dif){ //取到差 最小的,就是合最接近targert的值
                    compare = dif;
                    nsum =sum;
                }
            }
        }
        return nsum;
    }
}

相关文章

网友评论

    本文标题:LeetCode-array-3Sum Closest

    本文链接:https://www.haomeiwen.com/subject/xzhqhxtx.html