mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
leetcode new problems
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
The intuition in this problem is we first sort the entire list and then fix i on first index and j at i+1 and k at last index and then compute total ,if(total>0) then since it is sorted, we need to bring total down so we do k-- and if total<0 then j++
|
||||
|
||||
To avoid recomputations for same j, we do j++ until nums[j]!=nums[j-1]
|
||||
|
||||
TC : o(nlogn) + o(n*n); SC : o(1)
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
class Solution{
|
||||
public:
|
||||
vector<vector<int>> ThreeSum(vector<int> &nums){
|
||||
vector<vector<int>> res;
|
||||
sort(nums.begin(), nums.end());
|
||||
int n = nums.size();
|
||||
for(int i =0;i<n;i++){
|
||||
if(nums[i]>0) break;
|
||||
if(i>0 && nums[i]==nums[i-1]) continue;
|
||||
int j = i+1;
|
||||
int k = nums.size() -1;
|
||||
while(j<k){
|
||||
int total = nums[i]+nums[j]+nums[k];
|
||||
if(total>0) k--;
|
||||
else if(total<0) j++;
|
||||
else{
|
||||
res.push_back({nums[i], nums[j], nums[k]});
|
||||
j++;
|
||||
while(j<k && nums[j] == nums[j-1]) j++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user