Skip to content

Commit

Permalink
add four_sum
Browse files Browse the repository at this point in the history
  • Loading branch information
phinnl committed May 9, 2024
1 parent af8cb47 commit 65e845b
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/count_submatrices_with_all_ones.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// refer to https://leetcode.com/problems/count-submatrices-with-all-ones/

pub fn num_submat(mut matrix: Vec<Vec<i32>>) -> i32 {
let mut result = 0;
let len = matrix.len();
Expand Down
71 changes: 71 additions & 0 deletions src/four_sum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// refer to https://leetcode.com/problems/4sum/

pub fn four_sum(mut nums: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let mut result = Vec::new();
if nums.len() < 4 {
return result;
}

nums.sort();

for i in 0..nums.len() - 3 {
if i > 0 && nums[i] == nums[i - 1] {
continue;
}
for j in i + 1..nums.len() - 2 {
if j > i + 1 && nums[j] == nums[j - 1] {
continue;
}
let mut left = j + 1;
let mut right = nums.len() - 1;
while left < right {
if let Some(sum) = nums[i]
.checked_add(nums[j])
.and_then(|s| s.checked_add(nums[left]))
.and_then(|s| s.checked_add(nums[right]))
{
match sum.cmp(&target) {
std::cmp::Ordering::Equal => {
result.push(vec![nums[i], nums[j], nums[left], nums[right]]);
left += 1;
while left < right && nums[left] == nums[left - 1] {
left += 1;
}
}
std::cmp::Ordering::Greater => {
right -= 1;
}
std::cmp::Ordering::Less => {
left += 1;
}
}
} else {
left += 1;
}
}
}
}

result
}

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

#[test]
fn example_1() {
let nums = vec![1, 0, -1, 0, -2, 2];
let target = 0;
let expected = vec![vec![-2, -1, 1, 2], vec![-2, 0, 0, 2], vec![-1, 0, 0, 1]];
assert_eq!(four_sum(nums, target), expected);
}

#[test]
fn example_2() {
let nums = vec![2, 2, 2, 2, 2];
let target = 8;
let expected = vec![vec![2, 2, 2, 2]];
assert_eq!(four_sum(nums, target), expected);
}
}
2 changes: 2 additions & 0 deletions src/letter_combinations_of_a_phone_number.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// refer to https://leetcode.com/problems/letter-combinations-of-a-phone-number/

pub fn letter_combinations(digits: String) -> Vec<String> {
if digits.is_empty() {
return vec![];
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ pub mod best_time_to_buy_and_sell_stock;
pub mod maximum_different_between_increasing_elements;
pub mod count_submatrices_with_all_ones;
pub mod jump_game;
pub mod letter_combinations_of_a_phone_number;
pub mod letter_combinations_of_a_phone_number;
pub mod four_sum;

0 comments on commit 65e845b

Please sign in to comment.