259. 3Sum Smaller
Input: nums = [-2,0,1,3], and target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]int threeSumSmaller(vector<int>& nums, int target) { // time: O(n^2); space: O(1)
sort(nums.begin(), nums.end());
int res = 0, n = nums.size();
for (int i = 0; i < n - 2; ++i) {
int l = i + 1, r = n - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum < target) {
res += (r - l);
++l;
} else {
--r;
}
}
}
return res;
}Last updated