题目
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).
解法
暴力解法
暴力解法是最容易想到的,也最符合正常思路,那就是将数组中的所有三元组都找出来;这样就需要找到$\binom{n}{3}$种组合,所以大致的时间复杂度应该也是$O(n^3)$,这种算法思路简单,但是时间复杂度太大。
先排序后找三元组解法
这种解法是先将无序的数组变为有序,如果直接调用 C++ algorithm 库中的sort算法,大致排序时间应该是$O(nlgn)$。
之后在排序过后的数组中寻找三元组,寻找的方法是先固定数组(nums)中的一个元素 $x$ ,然后在该元素的左右分别设置两个下标索引 $l$ 和 $r$ ,当 $x + nums[l] + nums[r] < target$ 时,因为数组经过排序,所以就不用在意 $l$ 之前的元素,可以直接将 $r + 1$ 来寻找下一个三元组;反之亦然。
这种方法规避了许多不必要的三元组查找,在三元组查找的过程中时间复杂度只有 $O(n^2)$ ,所以该算法最后的时间复杂度是 $O(nlgn) + O(n^2)$ ,即 $O(n^2)$ 。
代码
暴力解法
无
先排序后找三元组解法
C++
1 | class Solution { |