0
点赞
收藏
分享

微信扫一扫

用Rust刷leetcode第十六题

夹胡碰 2022-11-07 阅读 68


Problem

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.

Example

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Constraints:

  • ​3 <= nums.length <= 10^3​
  • ​-10^3 <= nums[i] <= 10^3​
  • ​-10^4 <= target <= 10^4​

Solution

impl Solution {
pub fn three_sum_closest(nums: Vec<i32>, target: i32) -> i32 {
let mut temp = nums.clone();
temp.sort();
let (mut l, mut i, mut r): (i32, i32, i32) = (0, 1, 0);
let mut sum: i32 = 0;
let mut ret: i32 = 99999999;
while (i as usize) < temp.len()-1 {
l = i - 1;
r = i + 1;
while l >= 0 && (r as usize) < temp.len() {
sum = temp[i as usize ] + temp[l as usize ] + temp[r as usize];
if sum == target {
return sum;
}
if sum > target {
l -= 1;
} else {
r += 1;
}
if (sum - target).abs() < (ret - target).abs() {
ret = sum;
}
}
i += 1;
}
ret
}
}


举报

相关推荐

0 条评论