feat: 2364_count_number_of_bad_pairs
This commit is contained in:
parent
ef08c0ecb5
commit
7efd529fe3
7
2364_count_number_of_bad_pairs/Cargo.lock
generated
Normal file
7
2364_count_number_of_bad_pairs/Cargo.lock
generated
Normal file
@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "count_number_of_bad_pairs"
|
||||
version = "0.1.0"
|
6
2364_count_number_of_bad_pairs/Cargo.toml
Normal file
6
2364_count_number_of_bad_pairs/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "count_number_of_bad_pairs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
23
2364_count_number_of_bad_pairs/src/lib.rs
Normal file
23
2364_count_number_of_bad_pairs/src/lib.rs
Normal file
@ -0,0 +1,23 @@
|
||||
pub struct Solution;
|
||||
|
||||
impl Solution {
|
||||
pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
|
||||
let mut groups = std::collections::HashMap::<i32, i64>::new();
|
||||
|
||||
for (index, num) in nums.iter().enumerate() {
|
||||
let index_sub_num = index as i32 - *num;
|
||||
groups
|
||||
.entry(index_sub_num)
|
||||
.and_modify(|count| *count += 1)
|
||||
.or_insert(1);
|
||||
}
|
||||
|
||||
let total_comb = Solution::count_pairs(&(nums.len() as i64));
|
||||
let same_comb: i64 = groups.values().map(Solution::count_pairs).sum();
|
||||
total_comb - same_comb
|
||||
}
|
||||
|
||||
fn count_pairs(n: &i64) -> i64 {
|
||||
n * (n - 1) / 2
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user