Skip to content

Commit 21c5b71

Browse files
authored
Create 3Sum With Multiplicity.java
1 parent 01c7d2c commit 21c5b71

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Medium/3Sum With Multiplicity.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public int threeSumMulti(int[] nums, int target) {
3+
Arrays.sort(nums);
4+
long answer = 0;
5+
for (int i = 0; i < nums.length; i++) {
6+
int updatedTarget = target - nums[i];
7+
int startIdx = i + 1;
8+
int endIdx = nums.length - 1;
9+
while (startIdx < endIdx) {
10+
if (nums[startIdx] + nums[endIdx] < updatedTarget) {
11+
startIdx++;
12+
} else if (nums[startIdx] + nums[endIdx] > updatedTarget) {
13+
endIdx--;
14+
} else if (nums[startIdx] != nums[endIdx]) {
15+
int leftIdx = 1;
16+
int rightIdx = 1;
17+
while (startIdx + 1 < endIdx && nums[startIdx] == nums[startIdx + 1]) {
18+
leftIdx++;
19+
startIdx++;
20+
}
21+
while (endIdx - 1 > startIdx && nums[endIdx] == nums[endIdx - 1]) {
22+
rightIdx++;
23+
endIdx--;
24+
}
25+
26+
answer = (answer + leftIdx * rightIdx) % 1000000007;
27+
startIdx++;
28+
endIdx--;
29+
} else {
30+
answer = (answer + ((endIdx - startIdx + 1) * (endIdx - startIdx) / 2)) % 1000000007;
31+
break;
32+
}
33+
}
34+
}
35+
return (int) answer;
36+
}
37+
}

0 commit comments

Comments
 (0)