leetcode:3Sum Closest

Question: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).
给定一个含有n个数的数组S找到其中三个数使其最接近给定的数target,你可以假定每一次数组输入都有唯一的一个解。
算法思路:① 这个题和上一个题http://www.cnblogs.com/zhaolizhen/p/3Sum.html求三个数的和类似,但是要简单的多,其实还有更简单的方法,
抱着试试的心态,麻烦的穷举算法也能通过。
     ② 设置三个for循环,设置两个变量int temp=0;int n=Integer.MAX_VALUE;分别记录得到离target最近的值以及和target的差值。
代码设计:
 1 class Solution{
 2     public int threeSumClosest(int[] num, int target) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int temp=0;//记录最近的值
 6         int n=Integer.MAX_VALUE;//记录和target的差值
 7         for(int i=0;i<num.length;i++){//三重循环时间复杂度太高, 可是也没想起其他好办法
 8             for(int j=i+1;j<num.length;j++){
 9                 for(int k=j+1;k<num.length;k++){
10                     if(Math.abs(num[i]+num[j]+num[k]-target)<n){
11                         n=Math.abs(num[i]+num[j]+num[k]-target);
12                         temp=num[i]+num[j]+num[k];
13                     }
14                 }
15             }
16         }
17         return temp;
18     }
19 }
   这个题还有更简单的解法,就是对这个数组排序,然后设置两个指针,一个从前往后,一个从后往前进行遍历,判断三个数的和和target的差值,
记录下最小的并返回。

原文地址:https://www.cnblogs.com/zhaolizhen/p/3SumClosest.html