Skip to content

Commit f162e92

Browse files
Create 1512-number-of-good-pairs.java
1 parent 324f0e3 commit f162e92

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

java/1512-number-of-good-pairs.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/* Brute Force (Method 1)
2+
-----------------------------
3+
Time Complexity: O(n^2)
4+
Space Complexity: O(1)
5+
----------------------------*/
6+
class Solution {
7+
public int numIdenticalPairs(int[] nums) {
8+
int i=0,j=0,c=0;
9+
for(i=0;i<nums.length;i++){
10+
for(j=i+1;j<nums.length;j++){
11+
if(nums[i]==nums[j])
12+
c++;;
13+
}
14+
}
15+
return c;
16+
}
17+
}
18+
19+
/* Combinations (Method 2)
20+
---------------------------------
21+
Time Complexity: O(n)
22+
Space Complexity: O(n)
23+
---------------------------------*/
24+
class Solution {
25+
public int numIdenticalPairs(int[] nums) {
26+
Map<Integer, Integer> freq = new HashMap<>();
27+
for(int n: nums)
28+
freq.put(n, freq.getOrDefault(n, 0) + 1);
29+
int res = 0;
30+
for(int c : freq.values()){
31+
res += c*(c-1)/2; // Combination formula nC2 = n*n(n-1)/2
32+
}
33+
return res;
34+
}
35+
}
36+
37+
/* Method 3
38+
----------------------------
39+
Time Complexity: O(n)
40+
Space Complexity: O(n)
41+
---------------------------*/
42+
class Solution {
43+
public int numIdenticalPairs(int[] nums) {
44+
int res = 0;
45+
Map<Integer, Integer> freq = new HashMap<>();
46+
for(int n : nums){
47+
if(freq.containsKey(n)){
48+
res += freq.get(n);
49+
freq.put(n, freq.get(n)+1);
50+
}
51+
else
52+
freq.put(n, 1);
53+
}
54+
return res;
55+
}
56+
}

0 commit comments

Comments
 (0)