您的位置:首页 > 其它

LeetCode 259. 3Sum Smaller

2016-05-04 03:25 357 查看
Two pointers.

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

/*
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].
*/

int threeSumSmaller(vector<int>& nums, int target) {
if(nums.size() < 3) return 0;
sort(nums.begin(), nums.end());
int count = 0;
for(int i = 0; i < nums.size(); ++i) {
int start = i + 1;
int end = nums.size() - 1;
while(start < end) {
if(nums[i] + nums[start] + nums[end] < target) {
count += end - start;
start++;
} else {
end--;
}
}
}
return count;
}

int main(void) {
vector<int> nums{-2, 0, 1, 3};
cout << threeSumSmaller(nums, 2) << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: