LeetCode-16.3Sum Closest

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).

public int ThreeSumClosest(int[] nums, int target)
    {
       Array.Sort(nums);
            int front, back, sum,result;
            result= nums[0] +nums[1] + nums[2];
            for (int i = 0; i < nums.Length-2; i++)
            {
                front = i + 1;
                back = nums.Length - 1;
                while (front < back)
                {
                    sum = nums[i] + nums[front] + nums[back];
                    if (sum == target)
                      return sum;

                    if (Math.Abs(target-sum)< Math.Abs(target - result))
                    {
                        result = sum;
                    }
                    
                    if (sum > target)
                        back--;
                    else
                        front++;
                }
            }
            return result;
    }


你可能感兴趣的:(算法)