给你一个整数数组 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
解题思路:
class Solution {
public:
int numIdenticalPairs(vector<int>& nums) {
int ans = 0;
int counter[101];
memset(counter, 0, sizeof(counter));
for (auto n : nums) {
ans += counter[n]++;
}
return ans;
}
};
示例:
对于数组 [1, 3, 2, 1, 3, 1],遍历过程如下:
当 n 是 1 时,counter[1] 是 0,ans 增加 0,counter[1] 变成 1。
当 n 是 3 时,counter[3] 是 0,ans 增加 0,counter[3] 变成 1。
当 n 是 2 时,counter[2] 是 0,ans 增加 0,counter[2] 变成 1。
当 n 是 1 时,counter[1] 是 1,ans 增加 1,counter[1] 变成 2。
当 n 是 3 时,counter[3] 是 1,ans 增加 1,counter[3] 变成 2。
当 n 是 1 时,counter[1] 是 2,ans 增加 2,counter[1] 变成 3。