-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2364: Count Number of Bad Pairs
- Loading branch information
Showing
3 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
pub struct Solution; | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
use std::collections::hash_map::Entry; | ||
use std::collections::HashMap; | ||
|
||
impl Solution { | ||
pub fn count_bad_pairs(nums: Vec<i32>) -> i64 { | ||
let n = nums.len(); | ||
let mut counts = HashMap::new(); | ||
let mut good_pairs = 0; | ||
|
||
(0..).zip(nums).for_each(|(i, num)| { | ||
let key = num - i; | ||
|
||
match counts.entry(key) { | ||
Entry::Occupied(occupied_entry) => { | ||
let count = occupied_entry.into_mut(); | ||
|
||
good_pairs += *count; | ||
|
||
*count += 1; | ||
} | ||
Entry::Vacant(vacant_entry) => { | ||
vacant_entry.insert(1); | ||
} | ||
} | ||
}); | ||
|
||
let n = n as u64; | ||
|
||
(n * (n - 1) / 2 - good_pairs) as _ | ||
} | ||
} | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl super::Solution for Solution { | ||
fn count_bad_pairs(nums: Vec<i32>) -> i64 { | ||
Self::count_bad_pairs(nums) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
#[test] | ||
fn test_solution() { | ||
super::super::tests::run::<super::Solution>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
pub mod iterative; | ||
|
||
pub trait Solution { | ||
fn count_bad_pairs(nums: Vec<i32>) -> i64; | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::Solution; | ||
|
||
pub fn run<S: Solution>() { | ||
let test_cases = [(&[4, 1, 3, 3] as &[_], 5), (&[1, 2, 3, 4, 5], 0)]; | ||
|
||
for (nums, expected) in test_cases { | ||
assert_eq!(S::count_bad_pairs(nums.to_vec()), expected); | ||
} | ||
} | ||
} |