[Leetcode] 259. 3Sum Smaller 解题报告
2017-07-04 10:19
387 查看
题目:
Given an array of n integers nums and a target, find the number of index triplets
For example, given nums =
2.
Return 2. Because there are two triplets which sums are less than 2:
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;
}
};
Given an array of n integers nums and a target, find the number of index triplets
i, j, kwith
0 <= i < j < k < nthat 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;
}
};
相关文章推荐
- [leetcode] 259. 3Sum Smaller 解题报告
- 3Sum LeetCode 解题报告
- LeetCode 解题报告 3Sum Closest
- [Leetcode] 315. Count of Smaller Numbers After Self 解题报告
- LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum
- [leetcode] 15. 3Sum 解题报告
- 【LeetCode】3Sum 解题报告
- [LeetCode] 3Sum 解题报告
- leetcode解题报告15. 3Sum
- [LeetCode]3Sum,解题报告
- [LeetCode 解题报告]016. 3Sum Closest
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- leetcode解题报告16. 3Sum Closest
- [LeetCode 解题报告]015. 3Sum
- [leetcode] 315. Count of Smaller Numbers After Self 解题报告
- Leetcode 259. 3Sum Smaller (Medium) (cpp)
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- [LeetCode]259. 3Sum Smaller
- [Leetcode] 15. 3Sum 解题报告