用 Python 编写程序,查找第 i 个和第 j 个元素相同的 (i, j) 对的数量
pythonserver side programmingprogramming更新于 2026/2/1 4:28:17
假设我们有一个数组 nums。我们必须找到有多少对 (i,j),使得 nums[i] = nums[j],但 i 与 j 不同。
因此,如果输入为 nums = [1,3,1,3,5],则输出将为 4,因为对为 (0,2)、(2,0)、(1,3) 和 (3,1)
要解决这个问题,我们将遵循以下步骤 −
- d := a new map
- 对于 nums 中的每个 c,执行
- d[c] := (d[c] + 1),当 c 存在于 d 中时,否则为 1
- res := 0
- 对于每个 c,如果 c 位于元素列表中 (x,对于 d 中的所有 x,其中 d[x] > 1),执行
- res := res +(d[c] *(d[c]-1))
- 返回 res
示例
让我们看看下面的实现以便更好地理解 −
def solve(nums):
d = {}
for c in nums:
d[c] = d[c] + 1 if c in d.keys() else 1
res = 0
for c in (x for x in d if d[x] > 1):
res += (d[c] * (d[c]-1))
return res
nums = [1,3,1,3,5]
print(solve(nums))
输入
[1,3,1,3,5]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

