Question:
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(n^2) runtime?
分析:
题意要求给定一个有n个整数的数组和一个目标数据target,求解在数组中找到满足 0 <= i < j < k < n,且nums[i] + nums[j] + nums[k] < target. 的 三个下标i,j,k组的组数。
可以知道,数组元素的顺序并不影响下标i,j,k对应的三元素数组;比如【1,4,2,3】如果target为7,则i=0,j=2,k=3---【1,3,2】。更改数组顺序【1,2,3,4】下标为i=0,j=1,k=2但是对应的三元素数组仍为【1,2,3】.
所以在解决问题时候可以先将原数组从小到大排序。
此时,i从0开始。而j最初从i+1开始,k从n-1开始,如果nums[i] + nums[j] + nums[k] < target. ,这说明下标k在j~k之间的数组元素都满足要求,然后继续++j开始。否则k--。
代码如下:
<span style="font-size:14px;">class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size(), ans = 0, i, j, k;
for (int i = 0; i < n - 2; i++) {
int j = i + 1, k = n - 1;
while (j < k) {
if (nums[i] + nums[j] + nums[k] >= target) k--;
else {
ans += (k - j);
j++;
}
}
}
return ans;
}
};</span>