1512. Number of Good Pairs Easy
1/**
2 * [1512] Number of Good Pairs
3 *
4 * Given an array of integers nums, return the number of good pairs.
5 * A pair (i, j) is called good if nums[i] == nums[j] and i < j.
6 *
7 * Example 1:
8 *
9 * Input: nums = [1,2,3,1,1,3]
10 * Output: 4
11 * Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
12 *
13 * Example 2:
14 *
15 * Input: nums = [1,1,1,1]
16 * Output: 6
17 * Explanation: Each pair in the array are good.
18 *
19 * Example 3:
20 *
21 * Input: nums = [1,2,3]
22 * Output: 0
23 *
24 *
25 * Constraints:
26 *
27 * 1 <= nums.length <= 100
28 * 1 <= nums[i] <= 100
29 *
30 */
31pub struct Solution {}
32
33// problem: https://leetcode.com/problems/number-of-good-pairs/
34// discuss: https://leetcode.com/problems/number-of-good-pairs/discuss/?currentPage=1&orderBy=most_votes&query=
35
36// submission codes start here
37use std::collections::HashMap;
38
39impl Solution {
40 pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
41 let mut map: HashMap<i32, i32> = HashMap::new();
42 for n in nums {
43 map.entry(n).and_modify(|x| {*x += 1;}).or_insert(1);
44 }
45 let mut result = 0;
46 for (_, v) in map {
47 result += v * (v - 1) / 2;
48 }
49 result
50 }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn test_1512() {
61 assert_eq!(Solution::num_identical_pairs(vec![1,2,3,1,1,3]), 4);
62 }
63}
64
Back
© 2025 bowen.ge All Rights Reserved.