用Rust刷leetcode第十六题

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
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!