Python 查找良好对的数量程序


假设我们有一个数组 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 的大小

  • 对于 i 从 0 到 n - 1,执行

    • 对于 j 从 i+1 到 n - 1,执行

      • 如果 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]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

4

更新于: 2021年5月17日

3K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告