|
| 1 | +/** |
| 2 | + * [2364] Count Number of Bad Pairs |
| 3 | + * |
| 4 | + * You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i]. |
| 5 | + * Return the total number of bad pairs in nums. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: nums = [4,1,3,3] |
| 10 | + * Output: 5 |
| 11 | + * Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4. |
| 12 | + * The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1. |
| 13 | + * The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1. |
| 14 | + * The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2. |
| 15 | + * The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0. |
| 16 | + * There are a total of 5 bad pairs, so we return 5. |
| 17 | + * |
| 18 | + * Example 2: |
| 19 | + * |
| 20 | + * Input: nums = [1,2,3,4,5] |
| 21 | + * Output: 0 |
| 22 | + * Explanation: There are no bad pairs. |
| 23 | + * |
| 24 | + * |
| 25 | + * Constraints: |
| 26 | + * |
| 27 | + * 1 <= nums.length <= 10^5 |
| 28 | + * 1 <= nums[i] <= 10^9 |
| 29 | + * |
| 30 | + */ |
| 31 | +pub struct Solution {} |
| 32 | + |
| 33 | +// problem: https://leetcode.com/problems/count-number-of-bad-pairs/ |
| 34 | +// discuss: https://leetcode.com/problems/count-number-of-bad-pairs/discuss/?currentPage=1&orderBy=most_votes&query= |
| 35 | + |
| 36 | +// submission codes start here |
| 37 | + |
| 38 | +impl Solution { |
| 39 | + pub fn count_bad_pairs(nums: Vec<i32>) -> i64 { |
| 40 | + nums.into_iter() |
| 41 | + .enumerate() |
| 42 | + .map(|(i, num)| (i, num - i as i32)) |
| 43 | + .scan(std::collections::HashMap::new(), |map, (i, num)| { |
| 44 | + let same_count = map.entry(num).or_insert(0); |
| 45 | + let diff_count = i as i32 - *same_count; |
| 46 | + *same_count += 1; |
| 47 | + Some(diff_count as i64) |
| 48 | + }) |
| 49 | + .sum() |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// submission codes end |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | +mod tests { |
| 57 | + use super::*; |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn test_2364_example_1() { |
| 61 | + let nums = vec![4, 1, 3, 3]; |
| 62 | + |
| 63 | + let result = 5; |
| 64 | + |
| 65 | + assert_eq!(Solution::count_bad_pairs(nums), result); |
| 66 | + } |
| 67 | + |
| 68 | + #[test] |
| 69 | + fn test_2364_example_2() { |
| 70 | + let nums = vec![1, 2, 3, 4, 5]; |
| 71 | + |
| 72 | + let result = 0; |
| 73 | + |
| 74 | + assert_eq!(Solution::count_bad_pairs(nums), result); |
| 75 | + } |
| 76 | +} |
0 commit comments