Implemented p16, minor optimization in p15

This commit is contained in:
Egor 2024-04-30 12:18:12 +03:00
parent cede8e5f45
commit 8ea2584a1b
2 changed files with 25 additions and 8 deletions

View file

@ -13,13 +13,14 @@ impl Solution {
if k < nums.len() - 1 && nums[k + 1] == nums[k] {
k -= 1; continue;
}
match (nums[i] + nums[j] + nums[k]).cmp(&0) {
std::cmp::Ordering::Less => { j += 1; },
std::cmp::Ordering::Greater => { k -= 1 },
std::cmp::Ordering::Equal => {
match (nums[i] + nums[j] + nums[k]).signum() {
-1 => { j += 1; },
1 => { k -= 1 },
0 => {
result.push(vec![nums[i], nums[j], nums[k]]);
j += 1; k -= 1;
}
},
_ => ()
}
}
}

View file

@ -1,8 +1,24 @@
pub struct Solution;
impl Solution {
pub fn three_sum_closest(nums: Vec<i32>, target: i32) -> i32 {
return 0;
pub fn three_sum_closest(mut nums: Vec<i32>, target: i32) -> i32 {
let mut delta = i32::MAX / 2;
nums.sort();
for i in 0..nums.len()-2 {
if i > 0 && nums[i] == nums[i - 1] { continue; }
let (mut j, mut k) = (i + 1, nums.len() - 1);
while j < k {
let sum = nums[i] + nums[j] + nums[k];
let new_delta = sum - target;
match new_delta.signum() {
-1 => { j += 1; },
1 => { k -= 1 },
0 => { return target; },
_ => ()
}
if new_delta.abs() < delta.abs() { delta = new_delta; }
}
}
return target + delta;
}
}