2.1Leetcode好数对

给你一个整数数组 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。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值