用 Python 编写程序来计算数组元素相同的索引对

pythonserver side programmingprogramming更新于 2025/12/17 19:56:17

假设我们有一个名为 nums 的数字列表。我们必须找到 i < 的对数j 使得 nums[i] 和 nums[j] 相同。

因此,如果输入为 nums = [5, 4, 5, 4, 4],则输出将为 4,因为我们有索引对,如 (0, 2)、(1, 3)、(1, 4) 和 (3, 4)。

为了解决这个问题,我们将遵循以下步骤 −

  • c := 包含 nums 中每个元素出现频率的列表

  • count := 0

  • 对于 c 的所有值列表中的每个 n,执行

    • count := count + floor of (n *(n - 1)) / 2

  • 返回 count

示例

让我们看看下面的实现以便更好地理解

from collections import Counter
def solve(nums):
   c = Counter(nums)
   count = 0
   for n in c.values():
      count += n * (n - 1) // 2
   return count

nums = [5, 4, 5, 4, 4]
print(solve(nums))

输入

[5, 4, 5, 4, 4]

输出

4

相关文章


有用资源