|
2 | 2 |
|
3 | 3 | import java.util.Arrays; |
4 | 4 |
|
5 | | -/**259. 3Sum Smaller |
6 | | -
|
7 | | -Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. |
8 | | -
|
9 | | -For example, given nums = [-2, 0, 1, 3], and target = 2. |
10 | | -
|
11 | | -Return 2. Because there are two triplets which sums are less than 2: |
12 | | -
|
13 | | -[-2, 0, 1] |
14 | | -[-2, 0, 3] |
15 | | -
|
16 | | -Follow up: |
17 | | -Could you solve it in O(n2) runtime? */ |
18 | 5 | public class _259 { |
19 | 6 |
|
20 | | - /**Basically, very similar to 3Sum, but the key is that you'll have to add result by (right-left), not just increment result by 1!*/ |
21 | | - public int threeSumSmaller(int[] nums, int target) { |
22 | | - if (nums == null || nums.length == 0) { |
23 | | - return 0; |
24 | | - } |
25 | | - int result = 0; |
26 | | - Arrays.sort(nums); |
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 sum = nums[i] + nums[left] + nums[right]; |
32 | | - if (sum < target) { |
33 | | - result += right - left;//this line is key! |
34 | | - left++; |
35 | | - } else { |
36 | | - right--; |
| 7 | + public static class Solution1 { |
| 8 | + /** |
| 9 | + * Basically, very similar to 3Sum, but the key is that you'll have to add result by (right-left), not just increment result by 1! |
| 10 | + */ |
| 11 | + public int threeSumSmaller(int[] nums, int target) { |
| 12 | + if (nums == null || nums.length == 0) { |
| 13 | + return 0; |
| 14 | + } |
| 15 | + int result = 0; |
| 16 | + Arrays.sort(nums); |
| 17 | + for (int i = 0; i < nums.length - 2; i++) { |
| 18 | + int left = i + 1; |
| 19 | + int right = nums.length - 1; |
| 20 | + while (left < right) { |
| 21 | + int sum = nums[i] + nums[left] + nums[right]; |
| 22 | + if (sum < target) { |
| 23 | + result += right - left;//this line is key! |
| 24 | + left++; |
| 25 | + } else { |
| 26 | + right--; |
| 27 | + } |
37 | 28 | } |
38 | 29 | } |
| 30 | + return result; |
39 | 31 | } |
40 | | - return result; |
41 | 32 | } |
42 | 33 | } |
0 commit comments