-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum_With_Multiplicity.cpp
41 lines (41 loc) · 1.12 KB
/
3Sum_With_Multiplicity.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
int threeSumMulti(vector<int>& arr, int target) {
int mod = 1e9 + 7;
int ans = 0;
sort(arr.begin(),arr.end());
for(int i = 0 ; i < arr.size()-2; i++){
int t = target - arr[i];
int l = i+1;
int r = arr.size()-1;
while(l < r){
if(arr[l] + arr[r] < t){
l++;
}
else if(arr[l] + arr[r] > t){
r--;
}
else if(arr[l] != arr[r]){
int x = l;
while(arr[x] == arr[l]){
x++;
}
int y = r;
while(arr[y] == arr[r]){
y--;
}
ans += (x-l)*(r-y)%mod;
ans%=mod;
l = x;
r = y;
}
else{
ans += (r-l+1)*(r-l)/2;
ans %= mod;
break;
}
}
}
return ans;
}
};