LeetCode problem#1512
Number of Good Pairs
Solved in 1 languageC#
Solution
81 lines
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 // time O(n)
6 // space O(n)
7 public int NumIdenticalPairs(int[] nums) {
8 int count = 0;
9 Dictionary<int, int> dict = new Dictionary<int, int>();
10
11 for (int i = 0; i < nums.Length; i++)
12 {
13 if (dict.ContainsKey(nums[i]))
14 {
15 count += dict[nums[i]];
16 dict[nums[i]]++;
17 }
18 else
19 {
20 dict[nums[i]] = 1;
21 }
22 }
23
24 return count;
25 }
26
27 // time O(n^2)
28 // space O(1)
29 // public int NumIdenticalPairs(int[] nums) {
30 // int count = 0;
31
32 // for (int i = 0; i < nums.Length; i++)
33 // {
34 // for (int j = i + 1; j < nums.Length; j++)
35 // {
36 // if (nums[i] == nums[j])
37 // {
38 // count++;
39 // }
40 // }
41 // }
42
43 // return count;
44 // }
45
46 void Test()
47 {
48 int[] nums1 = {1,2,3,1,1,3};
49 int actual1 = NumIdenticalPairs(nums1);
50 if (actual1 != 4)
51 {
52 throw new Exception("Expected 4, but got " + actual1);
53 }
54
55 int[] nums2 = {1,1,1,1};
56 int actual2 = NumIdenticalPairs(nums2);
57 if (actual2 != 6)
58 {
59 throw new Exception("Expected 6, but got " + actual2);
60 }
61
62 int[] nums3 = {1,2,3};
63 int actual3 = NumIdenticalPairs(nums3);
64 if (actual3 != 0)
65 {
66 throw new Exception("Expected 0, but got " + actual3);
67 }
68
69 int[] nums4 = {6,5,1,5,7,7,9,1,5,7,1,6,10,9,7,4,1,8,7,1,1,8,6,4,7,4,10,5,3,9,10,1,9,5,5,4,1,7,4,2,9,2,6,6,4,2,10,3,5,3,6,4,7,4,6,4,4,6,3,4,10,1,10,6,10,4,9,6,6,4,8,6,9,5,4};
70 int actual4 = NumIdenticalPairs(nums4);
71 if (actual4 != 303)
72 {
73 throw new Exception("Expected 303, but got " + actual4);
74 }
75 }
76
77 public static void Main(string[] args)
78 {
79 new Solution().Test();
80 }
81}Want a walkthrough of this C# solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.