用 Python 编写程序来查找好对的数量
pythonserver side programmingprogramming更新于 2025/4/26 16:44:17
假设我们有一个数组 nums。如果 nums[i] 与 nums[j] 相同且 i < j,则称一对 (i,j) 为好对。我们必须计算好对的数量。
因此,如果输入为 nums = [5,6,7,5,5,7],则输出将为 4,因为有 4 个好对,索引为 (0, 3)、(0, 4) (3, 4)、(2, 5)
为了解决这个问题,我们将遵循以下步骤 −
count:= 0
n:= nums 的大小
对于 0 到 n - 1 范围内的 i,执行
对于 i+1 到 n - 1 范围内的 j,执行
如果 nums[i] 与 nums[j] 相同,则
count := count + 1
返回 count
示例 (Python)
让我们看看下面的实现以便更好地理解 −
def solve(nums): count=0 n=len(nums) for i in range(n): for j in range(i+1,n): if nums[i] == nums[j]: count+=1 return count nums = [5,6,7,5,5,7] print(solve(nums))
输入
[5,6,7,5,5,7]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

