|
3 | 3 | import java.util.Arrays;
|
4 | 4 |
|
5 | 5 | /**
|
6 |
| - * 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. |
| 6 | + * 16. 3Sum Closest |
| 7 | + * |
| 8 | + * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. |
| 9 | + * Return the sum of the three integers. You may assume that each input would have exactly one solution. |
7 | 10 | * For example, given array S = {-1 2 1 -4}, and target = 1.
|
8 | 11 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
|
9 | 12 | */
|
10 | 13 |
|
11 | 14 | public class _16 {
|
12 | 15 |
|
13 |
| - public int threeSumClosest(int[] nums, int target) { |
14 |
| - if (nums == null || nums.length == 0) { |
15 |
| - return 0; |
16 |
| - } |
17 |
| - Arrays.sort(nums); |
18 |
| - int len = nums.length; |
19 |
| - if (len < 3) { |
20 |
| - int sum = 0; |
21 |
| - for (int i : nums) { |
22 |
| - sum += i; |
| 16 | + public static class Solution1 { |
| 17 | + public int threeSumClosest(int[] nums, int target) { |
| 18 | + if (nums == null || nums.length == 0) { |
| 19 | + return 0; |
23 | 20 | }
|
24 |
| - return sum; |
25 |
| - } |
26 |
| - int sum = nums[0] + nums[1] + nums[2]; |
27 |
| - for (int i = 0; i < nums.length - 2; i++) { |
28 |
| - int left = i + 1; |
29 |
| - int right = nums.length - 1; |
30 |
| - while (left < right) { |
31 |
| - int thisSum = nums[i] + nums[left] + nums[right]; |
32 |
| - if (Math.abs(target - thisSum) < Math.abs(target - sum)) { |
33 |
| - sum = thisSum; |
34 |
| - if (sum == target) { |
35 |
| - return sum; |
| 21 | + Arrays.sort(nums); |
| 22 | + int len = nums.length; |
| 23 | + if (len < 3) { |
| 24 | + int sum = 0; |
| 25 | + for (int i : nums) { |
| 26 | + sum += i; |
| 27 | + } |
| 28 | + return sum; |
| 29 | + } |
| 30 | + int sum = nums[0] + nums[1] + nums[2]; |
| 31 | + for (int i = 0; i < nums.length - 2; i++) { |
| 32 | + int left = i + 1; |
| 33 | + int right = nums.length - 1; |
| 34 | + while (left < right) { |
| 35 | + int thisSum = nums[i] + nums[left] + nums[right]; |
| 36 | + if (Math.abs(target - thisSum) < Math.abs(target - sum)) { |
| 37 | + sum = thisSum; |
| 38 | + if (sum == target) { |
| 39 | + return sum; |
| 40 | + } |
| 41 | + } else if (target > thisSum) { |
| 42 | + left++; |
| 43 | + } else { |
| 44 | + right--; |
36 | 45 | }
|
37 |
| - } else if (target > thisSum) { |
38 |
| - left++; |
39 |
| - } else { |
40 |
| - right--; |
41 | 46 | }
|
42 | 47 | }
|
| 48 | + return sum; |
43 | 49 | }
|
44 |
| - return sum; |
45 | 50 | }
|
46 | 51 |
|
47 | 52 | }
|
0 commit comments