Number of Good Pairs

Given an array of integers nums array.

Find pair condition are: A pair (i,j) is called good if nums[i] == nums[j] and i < j.

Example

Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5).

Approach

Java

import java.util.HashMap;

public class GoodPair {
    public static void main(String[] args) {
        int nums[] = { 123113 };
        int gp = numIdenticalPairs(nums);
        System.out.println(gp);
    }

    public static int numIdenticalPairs(int[] nums) {
        HashMap<IntegerIntegerfMap =
             new HashMap<IntegerInteger>();
        int ngp = 0;
        for (int i = 0; i < nums.length; i++) {
            fMap.put(nums[i], 
            fMap.getOrDefault(nums[i], 0) + 1);
        }
        for (Integer k : fMap.keySet()) {
            int v = fMap.get(k);
            ngp += v * (v - 1) / 2;
        }
        return ngp;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int numIdenticalPairs(int nums[],int n
{
    map<int,intfMap;
    int ngp = 0;
    for (int i = 0i <ni++) 
    {
            fMap[nums[i]]++;
     }

    for(auto it=fMap.begin();it!=fMap.end();it++)
       {

           int p=it->second;
           ngp+=p*(p-1)/2;
       }
    return ngp;
}

int main()
{
    int nums[] = { 123113 };
    int n=sizeof(nums)/sizeof(nums[0]);
    int good_pair = numIdenticalPairs(nums,n);
    cout<<good_pair;
    return 0;
}


No comments:

Post a Comment