Completed 3sum leetcode question
This commit is contained in:
parent
9963b8ffd4
commit
8335d9c95f
43
src/leet.cpp
43
src/leet.cpp
@ -3,32 +3,39 @@
|
|||||||
|
|
||||||
std::vector<std::vector<int>> Solution::threeSum(std::vector<int>& nums) {
|
std::vector<std::vector<int>> Solution::threeSum(std::vector<int>& nums) {
|
||||||
std::vector<std::vector<int>> ans;
|
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
|
//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 i = 0; i < nums.size(); i++)
|
||||||
{
|
map[nums[i]] = i;
|
||||||
for (int j = i+1; j < nums.size(); j++)
|
|
||||||
{
|
|
||||||
sums[nums[i] + nums[j]] = std::vector<int>{i, j};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < nums.size(); i++)
|
for (int i = 0; i < nums.size(); i++)
|
||||||
{
|
{
|
||||||
if (sums.count(0-nums[i]))
|
if (nums[i] > 0)
|
||||||
{//If required value is in map
|
break;
|
||||||
std::vector<int> indexes = sums[0-nums[i]];
|
|
||||||
if (i == indexes[0] || i == indexes[1])
|
for (int j = i + 1; j < nums.size(); j++)
|
||||||
continue;
|
{
|
||||||
ans.push_back({ nums[i], nums[indexes[0]], nums[indexes[1]] });
|
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;
|
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
|
#pragma once
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <map>
|
#include <algorithm>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
std::vector<std::vector<int>> threeSum(std::vector<int>& nums);
|
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