包子君讲解的leetcode题目是越来越简单,在标题党的路上确实越走越远,对不起包子粉了😭
微信在美国被封这个现在还没有定论,估计北美的同学们没慌,但是父母亲戚们可能更着急。其实大可不必,首先被封的概率很小。其次怎么封?不管怎么封都有解决的办法,不管是VPN翻墙或者直接去用其他的app,老毛子无踪可寻的telegram,年青一代一直在玩的QQ,或者B端的钉钉,lark(没用过,正好试试)。在目前的阶段,大伙儿只要想联系,总是会有办法的。也许不看朋友圈视频号还能省点时间做点有意义的事情呢 🙃
Leetcode solution 1512. Number of Good Pairs
Blogger: https://blog.baozitraining.org/2020/07/leetcode-solution-1512-number-of-good.html
Youtube: https://youtu.be/dvnjvOLh88k
博客园: https://www.cnblogs.com/baozitraining/p/13338525.html
B站: https://www.bilibili.com/video/BV1hK4y1x7Py/
Problem Statement
Given an array of integers nums
.
A pair (i,j)
is called good if nums[i]
== nums[j]
and i
< j
.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
Problem link
Video Tutorial
You can find the detailed video tutorial here
Thought Process
Array is the most basic data structures and common solutions inclue
- Nested for loops O(N²)
- Sort O(NlgN)
- Use extra space O(N)
This applies to this problem perfectly. The O(N²) brute force solution is naive. We can also use a Map data structure (key is the number, value is the occurrence count) thus O(N). We can also sort the array and use this simple formula (also leetcode’s hint) to calculate the good number pair.
Good pairs = N * (N-1) / 2 where N is how many duplicate numbers, this is from combination C(n²), from n elements pick two
Solutions
Use Map
1 public int numIdenticalPairs(int[] nums) {
2 if (nums == null || nums.length == 0) {
3 return 0;
4 }
5
6 // key: int value; value: number of occurrence
7 Map<Integer, Integer> lookup = new HashMap<>();
8 int goodPairsCount = 0;
9 for (int i : nums) {
10 if (lookup.containsKey(i)) {
11 goodPairsCount += lookup.get(i);
12 lookup.put(i, lookup.get(i) + 1);
13 } else {
14 lookup.put(i, 1);
15 }
16 }
17
18 return goodPairsCount;
19 }
Time Complexity: O(N), N is the array size
Space Complexity: O(N) since we use extra Map
Sort
1 public int numIdenticalPairsWithSort(int[] nums) {
2 if (nums == null || nums.length == 0) {
3 return 0;
4 }
5
6 Arrays.sort(nums);
7
8 int goodPairsCount = 0;
9 int start = 0;
10 int end = 0;
11
12 while (end < nums.length) {
13 if (nums[end] == nums[start]) {
14 end++;
15 continue;
16 }
17 // if you have n occurrences of a number, the good pair is n*(n-1)/2, Cn^2
18 int delta = end - start;
19 if (delta > 1) {
20 goodPairsCount += delta * (delta - 1) / 2;
21 }
22 start = end;
23 }
24 // handle the case 1, 2, 3, 3, 3
25 if (start != nums.length - 1) {
26 goodPairsCount += (end - start) * (end - start - 1) / 2;
27 }
28 return goodPairsCount;
29 }
Time Complexity: O(NlgN), N is the array size since we sort
Space Complexity: O(1) no extra space is used
References
- None