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
解释:
唯一的特殊三元组是 (i, j, k) = (0, 1, 2)
,其中:
nums[0] = 6
,nums[1] = 3
,nums[2] = 6
nums[0] = nums[1] * 2 = 3 * 2 = 6
nums[2] = nums[1] * 2 = 3 * 2 = 6
示例 2:
输入: nums = [0,1,0,0]
输出: 1
解释:
唯一的特殊三元组是 (i, j, k) = (0, 2, 3)
,其中:
nums[0] = 0
,nums[2] = 0
,nums[3] = 0
nums[0] = nums[2] * 2 = 0 * 2 = 0
nums[3] = nums[2] * 2 = 0 * 2 = 0
示例 3:
输入: nums = [8,4,2,8,4]
输出: 2
解释:
共有两个特殊三元组:
(i, j, k) = (0, 1, 3)
nums[0] = 8
,nums[1] = 4
,nums[3] = 8
nums[0] = nums[1] * 2 = 4 * 2 = 8
nums[3] = nums[1] * 2 = 4 * 2 = 8
(i, j, k) = (1, 2, 4)
nums[1] = 4
,nums[2] = 2
,nums[4] = 4
nums[1] = nums[2] * 2 = 2 * 2 = 4
nums[4] = nums[2] * 2 = 2 * 2 = 4
提示:
3 <= n == nums.length <= 105
0 <= nums[i] <= 105
解法
方法一:枚举中间数字 + 哈希表
我们可以枚举中间数字 \(\textit{nums}[j]\),用两个哈希表 \(\textit{left}\) 和 \(\textit{right}\) 分别记录 \(\textit{nums}[j]\) 左侧和右侧的数字出现次数。
我们首先将所有数字加入 \(\textit{right}\) 中,然后从左到右遍历每个数字 \(\textit{nums}[j]\),在遍历过程中:
- 将 \(\textit{nums}[j]\) 从 \(\textit{right}\) 中移除。
- 计算 \(\textit{nums}[j]\) 左侧的数字 \(\textit{nums}[i] = \textit{nums}[j] * 2\) 的出现次数,记为 \(\textit{left}[\textit{nums}[j] * 2]\)。
- 计算 \(\textit{nums}[j]\) 右侧的数字 \(\textit{nums}[k] = \textit{nums}[j] * 2\) 的出现次数,记为 \(\textit{right}[\textit{nums}[j] * 2]\)。
- 将 \(\textit{left}[\textit{nums}[j] * 2]\) 和 \(\textit{right}[\textit{nums}[j] * 2]\) 相乘,得到以 \(\textit{nums}[j]\) 为中间数字的特殊三元组数量,并将结果累加到答案中。
- 将 \(\textit{nums}[j]\) 加入 \(\textit{left}\) 中。
最后返回答案。
时间复杂度为 \(O(n)\),空间复杂度为 \(O(n)\),其中 \(n\) 是数组 \(\textit{nums}\) 的长度。
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|