3583. 统计特殊三元组
问题
给你一个整数数组 nums。
特殊三元组 定义为满足以下条件的下标三元组 (i, j, k):
0 <= i < j < k < n,其中 n = nums.length
nums[i] == nums[j] * 2
nums[k] == nums[j] * 2
返回数组中 特殊三元组 的总数。
由于答案可能非常大,请返回结果对 109 + 7 取余数后的值。
示例 1:
输入: nums = [6,3,6]
输出: 1
分析
看了题解才会,枚举中间值,搜索两边存在几个2*中间值,然后相乘即可。显然,可以用哈希表存储。
代码
class Solution {
public:
long long res;
unordered_map<int, int> suf;
unordered_map<int, int> pre;
int n = 0;
int specialTriplets(vector<int>& nums) {
n = nums.size();
for (int i = 0; i < n; i++) {
suf[nums[i]] += 1;
}
for (int i = 0; i < n; i++) {
suf[nums[i]]--;
res = (res + 1LL * suf[2*nums[i]] * pre[2*nums[i]]) % (int)(1e9+7); // 注意这里不能用res+=,因为要加上原来的res后再取余。且要*1LL,因为要保证运算在long long中进行。
pre[nums[i]]++;
}
return res;
}
};

浙公网安备 33010602011771号