leetCode-15. 3Sum-Medium
descrition
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解析
方法1
3 重循环,时间复杂度-O(n^3),空间复杂度-O(1)
for(int i=0; i<array.size(); i++){
for(int j=i+1; j<array.size(); j++){
for(int k=j+1; k<array.size(); k++){
// 检查是否合法
}
}
}
方法2
思考方向:是否可以减少方法 1 中的循环查找次数??
时间复杂度-O(n^2),空间复杂度-O(1)。
对数组进行排序,需要时间 O(nlog(n))。使用两重循环,最外层循环 a=array[i],内层循环使用双向指针进行遍历,b 从左到右,c 从右到左,思想和 two sum 一样。(参看代码)
code
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
class Solution{
public:
vector<vector<int> > threeSum(vector<int>& nums){
// The solution set must not contain duplicate triplets.
vector<vector<int> > ans;
sort(nums.begin(), nums.end()); // ascending
for(int i=0; i<nums.size(); i++){
int target = -nums[i];
int ileft = i+1;
int iright = nums.size()-1;
while(ileft < iright){
int sum = nums[ileft]+nums[iright];
if( sum == target){
// answer
vector<int> temp(3);
temp[0] = nums[i];
temp[1] = nums[ileft];
temp[2] = nums[iright];
ans.push_back(temp);
// skip duplicate
while(ileft<iright && nums[ileft] == temp[1])
ileft++;
while(ileft<iright && nums[iright] == temp[2])
iright--;
}else if (sum < target){
ileft++;
}else{
// sum > target
iright--;
}
}
// skip duplicate
while((i+1)<nums.size() && nums[i+1] == nums[i])
i++;
// i point to the same value, after the i++ in the for loop, i will point to next value
}
return ans;
}
};
int main()
{
return 0;
}
作者:fanling999 链接:https://www.cnblogs.com/fanling999/