day 26: 268-missing-number, 15-3-sum

This commit is contained in:
Kaushik Narayan R 2023-10-25 15:13:29 -07:00
parent 191a4262d0
commit 06ceedd3ca
7 changed files with 109 additions and 0 deletions

18
15-3-sum/driver.cpp Normal file
View File

@ -0,0 +1,18 @@
#include "soln.hpp"
int main()
{
vector<int> nums{-2,0,1,1,2};
Solution soln;
vector<vector<int>> result = soln.threeSum(nums);
cout << "Three sum triplets:" << endl;
for (auto itr : result)
{
for (int num : itr)
{
cout << num << " ";
}
cout << endl;
}
return 0;
}

47
15-3-sum/soln.cpp Normal file
View File

@ -0,0 +1,47 @@
#include "soln.hpp"
vector<vector<int>> Solution::threeSum(vector<int> &nums)
{
vector<vector<int>> result;
sort(nums.begin(), nums.end());
int low, high, sum;
vector<int> new_triplet;
for (int i = 0; i < nums.size() - 2; i++)
{
if (i > 0 && nums[i] == nums[i - 1])
continue;
// two sum
int low = i + 1, high = nums.size() - 1;
while (low < high)
{
// if(nums[low] == nums[low-1]) {
// low++;
// continue;
// }
// if(nums[high] == nums[high+1]) {
// high--;
// continue;
// }
sum = nums[i] + nums[low] + nums[high];
if (sum == 0)
{
new_triplet = vector<int>{nums[i], nums[low], nums[high]};
// if(find(result.begin(), result.end(), new_triplet) == result.end()) {
result.push_back({nums[i], nums[low], nums[high]});
// }
low++;
while (nums[low] == nums[low - 1] && low < high)
low++;
}
else if (sum > 0)
{
high--;
}
else
{
low++;
}
}
}
return result;
}

7
15-3-sum/soln.hpp Normal file
View File

@ -0,0 +1,7 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums);
};

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> nums{9, 6, 4, 2, 3, 5, 7, 0, 1};
int answer = 8;
Solution soln;
cout << "Found missing number correctly? " << soln.test(nums, answer) << endl;
return 0;
}

View File

@ -0,0 +1,18 @@
#include "soln.hpp"
int Solution::missingNumber(vector<int> &nums)
{
int n = nums.size();
int calc_sum = (n * (n + 1)) / 2;
int act_sum = 0;
for (int num : nums)
{
act_sum += num;
}
return calc_sum - act_sum;
}
bool Solution::test(vector<int> &nums, int answer)
{
return missingNumber(nums) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int missingNumber(vector<int> &nums);
bool test(vector<int> &nums, int answer);
};

View File

@ -4,3 +4,4 @@
- essentials: bits/stdc++.h, iostream
- data structures: vector
- (q21)when working with structs, can't return locally created objects from a function, even when using new keyword...?
- 2sum, 3sum, palindrome, and other two pointer problems can prolly be identified by how they require comparison-based solutions across the entire array, and the array is to be sorted or ordered in some way for traversal