Skip to content

Commit 885b065

Browse files
MEDIUM/src/medium/_3Sum_Smaller.java
1 parent bb55054 commit 885b065

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

MEDIUM/src/medium/_3Sum_Smaller.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package medium;
2+
3+
import java.util.Arrays;
4+
5+
/**259. 3Sum Smaller
6+
7+
Total Accepted: 13428
8+
Total Submissions: 33743
9+
Difficulty: Medium
10+
11+
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.
12+
13+
For example, given nums = [-2, 0, 1, 3], and target = 2.
14+
15+
Return 2. Because there are two triplets which sums are less than 2:
16+
17+
[-2, 0, 1]
18+
[-2, 0, 3]
19+
20+
Follow up:
21+
Could you solve it in O(n2) runtime? */
22+
public class _3Sum_Smaller {
23+
24+
/**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!*/
25+
public int threeSumSmaller(int[] nums, int target) {
26+
if(nums == null || nums.length == 0) return 0;
27+
int result = 0;
28+
Arrays.sort(nums);
29+
for(int i = 0; i < nums.length-2; i++){
30+
int left = i+1, right = nums.length-1;
31+
while(left < right){
32+
int sum = nums[i] + nums[left] + nums[right];
33+
if(sum < target) {
34+
result += right-left;//this line is super cool!
35+
left++;
36+
} else right--;
37+
}
38+
}
39+
return result;
40+
}
41+
42+
}

0 commit comments

Comments
 (0)