题目:
Given an array of n integers nums and a target, find the number of index triplets i, j, k
with 0 <= i < j < k < n
that satisfy the condition nums[i] + nums[j] + nums[k] < target
.
For example, given nums = [-2, 0, 1, 3]
, and target = 2.
Return 2. Because there are two triplets which sums are less than 2:
[-2, 0, 1] [-2, 0, 3]
Follow up:
Could you solve it in O(n2) runtime?
思路:
由于本题目是求三个数的和,并且不要求返回索引位置(只要求返回符合条件的triple个数),所以可以首先花费O(nlogn)的时间复杂度进行排序。为了将时间复杂度降低到O(n^2),我们采用一个技巧,就是利用start的递增性和end的递减性。例如对于start = i + 1,假设我们找到了一个合适的end,使得i和[start, end]之间的数构成的triple都满足条件,那么对于start = i + 2, ... nums.size() - 2,其对应的end必然是逐渐递减的。因此,我们不需要对每个start都用二分法查找合适的end,只需要在第二重循环中,要么增加start,要么减少end(如果用普通的思路做,则算法的时间复杂度是O(n^2logn))。
代码:
class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
if(nums.size() < 3) {
return 0;
}
sort(nums.begin(), nums.end());
int ret = 0, sum = 0;
for(int i = 0; i < nums.size() - 2; ++i) {
int start = i + 1, end = nums.size() - 1;
while(start < end) {
sum = nums[i] + nums[start] + nums[end];
if(sum < target) {
ret += (end - start++); // all the ones satisfy the requirement
}
else {
--end;
}
}
}
return ret;
}
};