【LeetCode】C# 16、3Sum Closest

来源:互联网 发布:卷积神经网络 算法 编辑:程序博客网 时间:2024/06/05 22:34

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

给定一个数组,返回和最接近给定 target 的三个数。
这道题和上道一样,建立三个指针,遍历一遍nums作为第一个指针,后面通过与target对比决定start往右移还是end左移。

public class Solution {    public int ThreeSumClosest(int[] nums, int target) {        int res = nums[0] + nums[1] + nums[nums.Count() - 1];        Array.Sort(nums);        for (int i = 0; i < nums.Count() - 2; i++) {            int start = i + 1, end = nums.Count() - 1;            while (start < end) {                int temp = nums[i] + nums[start] + nums[end];                if (temp > target) {                    end--;                } else {                    start++;                }                if (Math.Abs(temp - target) < Math.Abs(res - target)) {                    res = temp;                }            }        }        return res;    }}

这里写图片描述