File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.Arrays;
2
+
3
+ /**
4
+ * @author Felix
5
+ * @date 2018年11月2日下午7:27:55
6
+ @version 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。
7
+ 返回这三个数的和。假定每组输入只存在唯一答案。例如,给定数组 nums = [ -1,2,1,-4] , 和 target = 1.
8
+ 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
9
+ * /
10
+ public class ThreeSumClosest {
11
+ public int threeSumClosest(int[ ] nums,int target){
12
+ int res = nums[ 0] + nums[ 1] +nums[ nums.length-1] ;
13
+ Arrays.sort(nums);//将数组排序
14
+ for(int first=0; first<nums.length-2; first++){//从0开始固定第一个数,第二三个数分别为剩下的边界
15
+ int second = first+1,third = nums.length-1;
16
+ while(second < third){
17
+ int sum = nums[ first] + nums[ second] + nums[ third] ;
18
+ if(sum < target){//数组已经从小到大排序,若sum<target,则第二个数向右走,相当于让sum值变大,更接近target
19
+ second++;
20
+ }else if(sum > target){//若小于则第三个数向左走,相当于让sum值变小,更接近target
21
+ third--;
22
+ }else{//相等则最接近target,直接返回
23
+ return sum;
24
+ }
25
+ res = Math.abs(sum-target)<Math.abs(res-target) ? sum : res;
26
+ }
27
+ }
28
+ return res;
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments