自学内容网 自学内容网

1512. 好数对的数目

目录

一:题目:

二:代码:

三:结果:


一:题目:

给你一个整数数组 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 result=0;
        unordered_map<int,int> ha;
        int n=nums.size();
        for(int i=0;i<n;i++){
            ha[nums[i]]++;
        }
        for(int i=0;i<n;i++){
            auto it=hashatble.find(nums[i]);
            if(it->second>=2){
                result+=it->second*(it->second-1)/2;
                it->second=0;
            }
        }
        return result;
    }
};

三:结果:


原文地址:https://blog.csdn.net/mrjieke6/article/details/142435177

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!