用Rust刷leetcode第十六題

linghuyichong發表於2020-09-05

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 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
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
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章