Skip to content

Commit

Permalink
Two sum ii input array is sorted (#198)
Browse files Browse the repository at this point in the history
* add two sum ii input array is sorted

* impl two sum ii input array is sorted
  • Loading branch information
SKTT1Ryze authored Mar 9, 2024
1 parent 8b4e648 commit b7564b2
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
44 changes: 44 additions & 0 deletions leetcode-cc/TwoSumIIInputArraySorted.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <unordered_map>

#include "TestHelper.h"
#include "problem.h"
#include "solution.h"

using namespace std;

IMPLEMENT_PROBLEM_CLASS(PTwoSumIIInputArraySorted, 167, DIFFI_MEDIUM,
TOPIC_ALGORITHMS, "Two Sum II - Input Array Is Sorted",
"", {"Hash Table"});

class STwoSumIIInputArraySorted : public ISolution {
public:
size_t problemId() const override { return 167; }
string name() const override {
return ("Solution for " + string("Two Sum II - Input Array is Sorted"));
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelper<pair<vector<int>, int>, vector<int>>(
{{{2, 7, 11, 15}, 9}, {{2, 3, 4}, 6}, {{-1, 0}, -1}},
{{1, 2}, {1, 3}, {1, 2}},
[this](auto input) { return this->twoSum(input.first, input.second); });
};
int benchmark() const override { return 0; }

private:
vector<int> twoSum(vector<int>& numbers, int target) const {
unordered_map<int, int> map = {};

for (int i = 0; i < numbers.size(); i++) {
int current = numbers[i];
int left = target - current;
if (map.contains(left)) {
return {map[left] + 1, i + 1};
} else {
map.insert({current, i});
}
}

return {};
}
};
8 changes: 8 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
#include "../leetcode-cc/ThreeSum.hpp"
#include "../leetcode-cc/ThreeSumClosest.hpp"
#include "../leetcode-cc/Triangle.hpp"
#include "../leetcode-cc/TwoSumIIInputArraySorted.hpp"
#include "../leetcode-cc/UniqueBinarySearchTrees.hpp"
#include "../leetcode-cc/UniqueBinarySearchTreesII.hpp"
#include "../leetcode-cc/UniqueNumOfOccurrences.hpp"
Expand Down Expand Up @@ -717,5 +718,12 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SFractionToDecimal>(); });

handle->registerProblem([]() -> ArcProblem {
return std::make_shared<PTwoSumIIInputArraySorted>();
});
handle->registerSolution([]() -> ArcSolution {
return std::make_shared<STwoSumIIInputArraySorted>();
});

return 0;
}

0 comments on commit b7564b2

Please sign in to comment.