Skip to content

Commit

Permalink
2563
Browse files Browse the repository at this point in the history
  • Loading branch information
warycat committed Nov 14, 2024
1 parent cc13ebb commit fc2d300
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
43 changes: 43 additions & 0 deletions leetcode/src/d25/_2563_count_the_number_of_fair_pairs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
struct Solution;

fn lower_bound(nums: &[i32], bound: i32) -> i64 {
let mut l = 0;
let mut r = nums.len() - 1;
let mut res = 0;
while l < r {
let sum = nums[l] + nums[r];
if sum < bound {
res += r - l;
l += 1;
} else {
r -= 1;
}
}
res as i64
}

impl Solution {
pub fn count_fair_pairs(mut nums: Vec<i32>, lower: i32, upper: i32) -> i64 {
nums.sort();
lower_bound(&nums, upper + 1) - lower_bound(&nums, lower)
}
}

#[test]
fn test() {
let nums = vec![0, 1, 7, 4, 4, 5];
let lower = 3;
let upper = 6;
let res = 6;
assert_eq!(Solution::count_fair_pairs(nums, lower, upper), res);
let nums = vec![1, 7, 9, 2, 5];
let lower = 11;
let upper = 11;
let res = 1;
assert_eq!(Solution::count_fair_pairs(nums, lower, upper), res);
let nums = vec![0, 0, 0, 0, 0, 0];
let lower = 0;
let upper = 0;
let res = 15;
assert_eq!(Solution::count_fair_pairs(nums, lower, upper), res);
}
1 change: 1 addition & 0 deletions leetcode/src/d25/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mod _2563_count_the_number_of_fair_pairs;
2 changes: 1 addition & 1 deletion leetcode/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ mod d16;
mod d17;
mod d18;
mod d19;
//
mod d20;
mod d21;
mod d25;

0 comments on commit fc2d300

Please sign in to comment.