Completed 3sum leetcode question
This commit is contained in:
parent
9963b8ffd4
commit
8335d9c95f
45
src/leet.cpp
45
src/leet.cpp
@ -3,32 +3,39 @@
|
||||
|
||||
std::vector<std::vector<int>> Solution::threeSum(std::vector<int>& nums) {
|
||||
std::vector<std::vector<int>> ans;
|
||||
std::unordered_map<int, int> map;
|
||||
|
||||
std::sort(nums.begin(), nums.end());
|
||||
|
||||
if (nums.size() < 3) { // Base Case 1
|
||||
return {};
|
||||
}
|
||||
if (nums[0] > 0) { // Base Case 2
|
||||
return {};
|
||||
}
|
||||
|
||||
//itterate through map O(n^2) and create a map of the sums of each element
|
||||
for (int i = 0; i < nums.size(); i++)
|
||||
{
|
||||
for (int j = i+1; j < nums.size(); j++)
|
||||
{
|
||||
sums[nums[i] + nums[j]] = std::vector<int>{i, j};
|
||||
}
|
||||
}
|
||||
map[nums[i]] = i;
|
||||
|
||||
for (int i = 0; i < nums.size(); i++)
|
||||
{
|
||||
if (sums.count(0-nums[i]))
|
||||
{//If required value is in map
|
||||
std::vector<int> indexes = sums[0-nums[i]];
|
||||
if (i == indexes[0] || i == indexes[1])
|
||||
continue;
|
||||
ans.push_back({ nums[i], nums[indexes[0]], nums[indexes[1]] });
|
||||
if (nums[i] > 0)
|
||||
break;
|
||||
|
||||
for (int j = i + 1; j < nums.size(); j++)
|
||||
{
|
||||
int numNeeded = (nums[i] + nums[j]) * -1;
|
||||
if (map.count(numNeeded) && map.find(numNeeded)->second > j)
|
||||
ans.push_back({ nums[i], nums[j], numNeeded });
|
||||
|
||||
//Update J to avoid duplicates
|
||||
j = map.find(nums[j])->second;
|
||||
}
|
||||
|
||||
//Update i to avoid duplicates
|
||||
i = map.find(nums[i])->second;
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
|
||||
//
|
||||
//Given an integer array nums, return all the triplets[nums[i], nums[j], nums[k]]
|
||||
// such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
|
||||
//
|
||||
//Notice that the solution set must not contain duplicate triplets.
|
||||
}
|
@ -1,11 +1,9 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <algorithm>
|
||||
#include <unordered_map>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
std::vector<std::vector<int>> threeSum(std::vector<int>& nums);
|
||||
private:
|
||||
//Map of sum + indexes
|
||||
std::map<int, std::vector<int>> sums;
|
||||
};
|
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue
Block a user