Skip to content

Commit

Permalink
Add problem 1995: Count Special Quadruplets
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 7, 2024
1 parent a8abed9 commit 65900ee
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,7 @@ pub mod problem_1985_find_the_kth_largest_integer_in_the_array;
pub mod problem_1986_minimum_number_of_work_sessions_to_finish_the_tasks;
pub mod problem_1991_find_the_middle_index_in_array;
pub mod problem_1994_the_number_of_good_subsets;
pub mod problem_1995_count_special_quadruplets;
pub mod problem_1996_the_number_of_weak_characters_in_the_game;
pub mod problem_2000_reverse_prefix_of_word;
pub mod problem_2006_count_number_of_pairs_with_absolute_difference_k;
Expand Down
56 changes: 56 additions & 0 deletions src/problem_1995_count_special_quadruplets/hash_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::collections::hash_map::Entry;
use std::collections::HashMap;

impl Solution {
pub fn count_quadruplets(nums: Vec<i32>) -> i32 {
let nums = nums.as_slice();
let n = nums.len();

assert!(n > 3);

let mut sums = HashMap::new();

sums.insert(nums[0] + nums[1], 1);

let mut result = 0;

for i in 2..n - 1 {
let num = nums[i];

for &forth in &nums[i + 1..] {
result += sums.get(&(forth - num)).copied().unwrap_or(0);
}

for &first in &nums[..i] {
match sums.entry(first + num) {
Entry::Occupied(entry) => *entry.into_mut() += 1,
Entry::Vacant(entry) => {
entry.insert(1);
}
}
}
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn count_quadruplets(nums: Vec<i32>) -> i32 {
Self::count_quadruplets(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_1995_count_special_quadruplets/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod hash_map;

pub trait Solution {
fn count_quadruplets(nums: Vec<i32>) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [(&[1, 2, 3, 6] as &[_], 1), (&[3, 3, 6, 4, 5], 0), (&[1, 1, 1, 3, 5], 4)];

for (nums, expected) in test_cases {
assert_eq!(S::count_quadruplets(nums.to_vec()), expected);
}
}
}

0 comments on commit 65900ee

Please sign in to comment.