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[] = { 1, 2, 3, 1, 1, 3 };int gp = numIdenticalPairs(nums);System.out.println(gp);}public static int numIdenticalPairs(int[] nums) {HashMap<Integer, Integer> fMap =new HashMap<Integer, Integer>();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,int> fMap;int ngp = 0;for (int i = 0; i <n; i++){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[] = { 1, 2, 3, 1, 1, 3 };int n=sizeof(nums)/sizeof(nums[0]);int good_pair = numIdenticalPairs(nums,n);cout<<good_pair;return 0;}
No comments:
Post a Comment