3583: 统计特殊三元组
三变量问题,一般枚举中间的变量最简单。
为什么?对比一下:
- 枚举 i,后续计算中还需保证 j<k。
- 枚举 j,那么 i 和 k 自动被 j 隔开,互相独立,后续计算中无需关心 i 和 k 的位置关系。
思路:
由于答案不超过 n⋅10^5⋅10^5≤10^15,可以只在返回时取模。
class Solution {
public:
int specialTriplets(vector<int>& nums) {
constexpr int MOD=1'000'000'007;
unordered_map<int,int> suf;
for(int x :nums) suf[x]++;
long long ans=0;
unordered_map<int,int> pre;
for(int x :nums){
suf[x]--;
// 现在 pre 中的是 [0,j-1],suf 中的是 [j+1,n-1]
ans+=(long long)pre[x*2]*suf[x*2];
pre[x]++;
}
return ans%MOD;
}
};