算法題丨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.git

示例

Given array S = {-1 2 1 -4}, and target = 1.

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

算法分析

難度:中
分析:給定整型數組中和一個指定的目標整型值,從數組中找到3個元素,知足3個元素之和最接近目標值,返回結果爲3個元素之和。
思路:大致思路相似3Sum算法,也是先將數組排序,而後開始遍歷,3個元素分別是當前遍歷的元素、夾逼開始元素默認當前元素後面的元素,夾逼結束元素默認數組最後的元素,經過夾逼開始元素遞增和夾逼結束元素遞減來實現夾逼:
 1. 若是這3個元素之和比目標值大,則須要夾逼結束元素值變小,纔有可能接近目標值,因此夾逼結束元素遞減;
 2. 若是這3個元素之和不比目標值大,則須要夾逼開始元素值變大,纔有可能接近目標值,因此夾逼開始元素遞增;
本次遍歷結束後,再判斷本次3元素之和目前記錄的最接近之和比較,取更接近的作爲返回結果,而後繼續遍歷,直至遍歷結果,得到返回結果。github

代碼示例(C#)

public int ThreeSumClosest(int[] nums, int target)
{
    int res = nums[0] + nums[1] + nums[nums.Length - 1];

    //排序後遍歷
    Array.Sort(nums);
    for (int i = 0; i < nums.Length - 2; i++)
    {
        //從當先後面的元素和最後一個元素,兩邊夾逼
        int lo = i + 1, hi = nums.Length - 1;
        while (lo < hi)
        {
            int sum = nums[i] + nums[lo] + nums[hi];
            if (sum > target)
            {
                hi--;
            }
            else
            {
                lo++;
            }
            //若是這次遍歷的3個元素的和更接近,則賦值返回的結果
            if (Math.Abs(sum - target) < Math.Abs(res - target))
            {
                res = sum;
            }
        }
    }
    return res;
}

複雜度

  • 時間複雜度O (n²).
  • 空間複雜度O (1).

附錄

相關文章
相關標籤/搜索