C#LeetCode刷题之#16-最接近的三数之和(3Sum Closest)

C#LeetCode刷题之#16-最接近的三数之和(3Sum Closest)

问题

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

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.

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

示例

public class Program {

    public static void Main(string[] args) {
        var intervals = new int[] { -1, 2, 1, -4 };
        var target = 1;

        var res = ThreeSumClosest(intervals, target);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    public static int ThreeSumClosest(int[] nums, int target) {
        //基础思路同“3数之和”
        Array.Sort(nums);
        //定义结果、3数之和
        var res = 0;
        var sum = 0;
        //定义上一次和这一次的差
        var prediff = int.MaxValue;
        var diff = 0;
        //定义左右双指针
        var j = 0;
        var k = 0;
        //双指针 j、k 循环分析
        for(var i = 0; i < nums.Length - 2; i++) {
            j = i + 1;
            k = nums.Length - 1;
            //左指针不能大于或等于右指针
            while(j < k) {
                sum = nums[i] + nums[j] + nums[k];
                //3数之和与目标值比
                //根据结果移动左右指针或相等时直接返回结果
                if(sum > target) k--;
                else if(sum < target) j++;
                else return sum;
                //计算差值
                diff = Math.Abs(sum - target);
                //如果本次更小,重置结果和“上一次差值”
                if(diff < prediff) {
                    res = sum;
                    prediff = diff;
                }
            }
        }
        //返回结果
        return res;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

2

分析

显而易见, 以上算法的时间复杂度为:O(n^2)O(n2) 。

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3620

发表评论

登录后才能评论