题目描述
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
题目分析
题目让我们返回一组数中重复数字的pair的个数,并且每一对数字中,第一个数的位数比第二个数的位数小。
方案一(brute force)
用两个循环遍历数组,第二个循环从第一个循环的当前值+1
开始循环。当第二个循环遇到第一个循环的当前数值时,就让计数+1.
方案二(等差数列)
只用一个循环,并且使用Python自带的 colllections库的 Counter。Counter形成的是一个字典,其中每一个元素是Key, 其个数是values。
以example 2为例, nums = [1,1,1,1]
用位数为 0 的 ‘1’ 去找相同并且位数大于自己的数,有3种情况(这里都列的是位数):[0,1], [0,2], [0,3]
用位数为 1 的 ‘1’ 去找相同并且位数大于自己的数,有2种情况:[1,2], [1,3]
用位数为 2 的 ‘1’ 去找相同并且位数大于自己的数,有1种情况:[2,3]
用位数为 3 的 ‘1’ 去找相同并且位数大于自己的数,有0种情况
总共有6种情况,6= 3+2+1,这个规律也适用于其他情况,所以是可以用等差数列来求得某一个数所有的组合情况。
代码实现
方案一(brute force)
class Solution(object):
def numIdenticalPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
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
方案二(等差数列)
class Solution(object):
def numIdenticalPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
count = collections.Counter(nums)
for k in count:
if count[k]>1: # collections.Counter这里[k], 返回的是某个element的个数
ans += count[k]*(count[k]-1)/2 # 公式是(首项+末项)*项数/2
# = (1+(n-1))*(n-1)/2 =n(n-1)/2
return ans
日期
2021-1-31 #1512 方案一&二