Skip to content

Commit d4f9774

Browse files
committed
solve aylei#16
1 parent cbfd5ac commit d4f9774

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ mod n0012_integer_to_roman;
1313
mod n0013_roman_to_integer;
1414
mod n0014_longest_common_prefix;
1515
mod n0015_3sum;
16+
mod n0016_3sum_closest;

src/n0016_3sum_closest.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* [16] 3Sum Closest
3+
*
4+
* Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
5+
*
6+
* Example:
7+
*
8+
*
9+
* Given array nums = [-1, 2, 1, -4], and target = 1.
10+
*
11+
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
12+
*
13+
*
14+
*/
15+
pub struct Solution {}
16+
17+
// submission codes start here
18+
19+
impl Solution {
20+
pub fn three_sum_closest(nums: Vec<i32>, target: i32) -> i32 {
21+
let mut nums = nums;
22+
let mut min_distance: i32 = i32::max_value();
23+
nums.sort();
24+
let mut i = 0;
25+
while i < nums.len() - 2 {
26+
let sub_min = Solution::two_sum_closest(&nums[(i+1)..nums.len()], target - nums[i]);
27+
if sub_min.abs() < min_distance.abs() {
28+
min_distance = sub_min;
29+
if min_distance == 0 { break }
30+
}
31+
i += 1;
32+
}
33+
target + min_distance
34+
}
35+
36+
pub fn two_sum_closest(nums: &[i32], target: i32) -> i32 {
37+
let (mut i, mut j) = (0_usize, nums.len() - 1);
38+
let mut local_min = i32::max_value();
39+
while i < j {
40+
let sum = nums[i] + nums[j];
41+
if sum > target { j -= 1; }
42+
else if sum < target { i += 1; }
43+
else { return 0 }
44+
if (sum - target).abs() < local_min.abs() {
45+
local_min = sum - target
46+
}
47+
}
48+
local_min
49+
}
50+
}
51+
52+
// submission codes end
53+
54+
#[cfg(test)]
55+
mod tests {
56+
use super::*;
57+
58+
#[test]
59+
fn test_16() {
60+
assert_eq!(Solution::three_sum_closest(vec![-1, 2, 1, -4], 1), 2);
61+
assert_eq!(Solution::three_sum_closest(vec![1, 2, 3], 1), 6);
62+
assert_eq!(Solution::three_sum_closest(vec![1,2,4,8,16,32,64,128], 82), 82);
63+
}
64+
}

0 commit comments

Comments
 (0)