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

Java源码

`package com.maoxiaomeng;/** * @author lihui * @date 2018/3/26 12:31 */public class Solution {    public int threeSumClosest(int[] nums, int target) {        int closest = Integer.MAX_VALUE;        int sum = 0;        int len = nums.length;                for (int i = 0; i < len - 2; i++) {            for (int j = i + 1; j < len - 1; j++) {                for (int k = j + 1; k < len; k++) {                    int temp = nums[i] + nums[j] + nums[k] - target;                    if (temp < 0) {                        temp = -temp;                    }                    if (temp < closest) {                        closest = temp;                        sum = nums[i] + nums[j] + nums[k];                    }                                    }            }        }                return sum;    }}`

`package com.maoxiaomeng;import java.util.Arrays;/** * @author lihui * @date 2018/3/26 12:31 */public class Solution {    public int threeSumClosest(int[] nums, int target) {        int minSum = 0;        int closest = Integer.MAX_VALUE;        Arrays.sort(nums);        int len = nums.length;        for (int i = 0; i < len - 2; i++) {            int left = i + 1;            int right = len - 1;            while (left < right) {                int sum = nums[i] + nums[left] + nums[right];                //-1, 1, 2, -4}                //i left    right                if (sum < target) {                    left++;                } else if (sum > target) {                    right--;                } else {                    return target;                }                int temp = sum - target;                if (temp < 0) {                    temp = -temp;                }                if (closest > temp) {                    closest = temp;                    minSum = sum;                }                            }        }                return minSum;    }}`