package com.learn.mianshi;
import java.util.Arrays;
public class ThreeSumTarget {
public static void main(String[] args) {
int[] array = {-1, 2, 1, -4};
System.out.println(threeSum(array,1));
}
public static int threeSum (int[] array,int target) {
if (null == array) {
return 0;
}
int len = array.length;
if (len <= 0) {
return 0;
}
if (len == 1) {
return array[0];
}
if (len == 2) {
return array[0]+array[1];
}
if (len == 3) {
return array[0]+array[1]+array[2];
}
Arrays.sort(array);
int sum = array[0]+array[1]+array[2];
for (int i=0;i<len;i++) {
int start = i+1;
int end = len-1;
while (start < end) {
int temp = array[start]+array[end]+array[i];
// 接近
if (Math.abs(target-sum) > Math.abs(target-temp)) {
sum = temp;
} else if (temp > target) {
end--;
} else if (temp < target) {
start++;
} else {
return sum;
}
}
}
return sum;
}
}
06-07
700
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-12
266
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交