Given an array of n integers nums and an integer 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.
- Time : O(n^2)
- Space : O(1)
1 | class Solution { |
- Time : O(n^2logn)
Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
int res = 0;
for(int i = nums.size() - 3; i >= 0; --i) {
sort(nums.begin() + i + 1, nums.end());
for(int j = i + 1; j < nums.size() - 1; j++) {
int t = target - nums[i] - nums[j];
auto it = lower_bound(nums.begin() + j + 1, nums.end(), t);
if(it == nums.begin() + j + 1) break;
res += it - (nums.begin() + j + 1);
}
}
return res;
}
};Time : O(n^2)
- Space : O(n)
1 | class Solution { |