Skip to content

Commit c870701

Browse files
refactor 259
1 parent f6faa99 commit c870701

File tree

1 file changed

+22
-31
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+22
-31
lines changed

src/main/java/com/fishercoder/solutions/_259.java

Lines changed: 22 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,41 +2,32 @@
22

33
import java.util.Arrays;
44

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? */
185
public class _259 {
196

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+
}
3728
}
3829
}
30+
return result;
3931
}
40-
return result;
4132
}
4233
}

0 commit comments

Comments
 (0)