给你一个整数数组 nums
。
如果一组数字 (i,j)
满足 nums[i]
== nums[j]
且 i
< j
,就可以认为这是一组 好数对 。
返回好数对的数目。
示例 1:
输入:nums = [1,2,3,1,1,3] 输出:4 解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始
示例 2:
输入:nums = [1,1,1,1] 输出:6 解释:数组中的每组数字都是好数对
示例 3:
输入:nums = [1,2,3] 输出:0
提示:
1 <= nums.length <= 100
1 <= nums[i] <= 100
提示 1
Count how many times each number appears. If a number appears n times, then n * (n – 1) // 2 good pairs can be made with this number.
解法:哈希表
Java版:
class Solution {
public int numIdenticalPairs(int[] nums) {
int ans = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.merge(nums[i], 1, Integer::sum) > 1) {
ans += map.get(nums[i]) - 1;
}
}
return ans;
}
}
Python版:
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
dict_ = {}
ans = 0
for num in nums:
dict_[num] = dict_[num] + 1 if num in dict_ else 1
if dict_[num] > 1:
ans += dict_[num] - 1
return ans
复杂度分析
- 时间复杂度:O(n),n为数组nums的长度。
- 空间复杂度:O(k),k为nums中不同元素的个数。