File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments