8000 Roughly commit · fibers/ex-algorithm@6a0964f · GitHub
[go: up one dir, main page]

Skip to content

Commit 6a0964f

Browse files
committed
Roughly commit
1 parent a9a433f commit 6a0964f

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed
Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,36 @@
11
package com.fibers.algorithm.leetcode._016;
2+
3+
import java.util.Arrays;
4+
25
public class Solution {
6+
public int threeSumClosest(int[] nums, int target) {
7+
if (nums == null || nums.length < 3) {
8+
return 0;
9+
}
10+
11+
Arrays.sort(nums);
12+
int result = nums[0] + nums[1] + nums[2];
13+
14+
for (int i = 0; i < nums.length - 2; i++) {
15+
int start = i + 1;
16+
int end = nums.length - 1;
17+
while (start < end) {
18+
int sum = nums[i] + nums[start] + nums[end];
19+
20+
if (Math.abs(sum - target) < Math.abs(result - target)) {
21+
result = sum;
22+
}
23+
24+
if (sum > targ 7945 et) {
25+
end--;
26+
} else if (sum < target) {
27+
start++;
28+
} else {
29+
return sum;
30+
}
31+
}
32+
}
33+
return result;
34+
}
335
}
4-
36+

0 commit comments

Comments
 (0)
0