From a56ab94527b537e12d7ca59454aa50d083f4a576 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 17 Nov 2024 15:29:11 +0800 Subject: [PATCH] 20241117 finished. --- src/problem/mod.rs | 2 + .../p825_friends_of_appropriate_ages.rs | 62 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/problem/p825_friends_of_appropriate_ages.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index cf4f537..08845b6 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -320,3 +320,5 @@ mod p3249_count_the_number_of_good_nodes; mod p3239_minimum_number_of_flips_to_make_binary_grid_palindromic_i; mod p3240_minimum_number_of_flips_to_make_binary_grid_palindromic_ii; + +mod p825_friends_of_appropriate_ages; diff --git a/src/problem/p825_friends_of_appropriate_ages.rs b/src/problem/p825_friends_of_appropriate_ages.rs new file mode 100644 index 0000000..71b3e7a --- /dev/null +++ b/src/problem/p825_friends_of_appropriate_ages.rs @@ -0,0 +1,62 @@ +/** + * [825] Friends Of Appropriate Ages + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn num_friend_requests(ages: Vec) -> i32 { + let n = ages.len(); + let mut ages = ages; + ages.sort_unstable(); + + let mut result = 0; + + for i in (0..n).rev() { + let lower_bound = ages[i] / 2 + 7; + if lower_bound >= ages[i] { + continue; + } + + let mut j = i + 1; + while j < n && ages[j] == ages[i] { + result += 1; + j += 1; + } + + match ages.binary_search(&lower_bound) { + Ok(pos) => { + let mut pos = pos; + while pos + 1 < n && ages[pos] == ages[pos + 1] { + pos += 1; + } + + result += i - pos - 1; + } + Err(pos) => { + result += i - pos; + } + } + } + + result as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_825() { + assert_eq!(2, Solution::num_friend_requests(vec![16, 16])); + assert_eq!(2, Solution::num_friend_requests(vec![16, 17, 18])); + assert_eq!( + 3, + Solution::num_friend_requests(vec![20, 30, 100, 110, 120]) + ); + } +}