Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find peak element #194

Merged
merged 2 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions leetcode-cc/FindPeakElement.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <algorithm>

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

using namespace std;

IMPLEMENT_PROBLEM_CLASS(PFindPeakElement, 162, DIFFI_MEDIUM, TOPIC_ALGORITHMS,
"Find Peak Element", "", {""});

class SFindPeakElement : public ISolution {
public:
size_t problemId() const override { return 162; }
string name() const override {
return ("Solution for " + string("Find Peak Element"));
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelper<vector<int>, int>(
{{1, 2, 3, 1}, {1, 2, 1, 3, 5, 6, 4}}, {2, 1},
[this](auto input) { return this->findPeakElement(input); });
};
int benchmark() const override { return 0; }

private:
int findPeakElement(vector<int>& nums) const {
int n = nums.size();
if (n == 1) return 0;
if (n == 2) return nums[0] < nums[1] ? 1 : 0;

if (nums[0] > nums[1]) {
return 0;
}

int prev = 0;
int current = 1;
int next = 2;

while (next <= n) {
if (next == n) {
return nums[prev] < nums[current] ? current : prev;
} else if (nums[prev] < nums[current] && nums[next] < nums[current]) {
return current;
} else {
prev++;
current++;
next++;
}
}

return -1;
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "../leetcode-cc/EvaluateReversePolishNotation.hpp"
#include "../leetcode-cc/FindMinInRotatedSortedArray.hpp"
#include "../leetcode-cc/FindMinInRotatedSortedArrayII.hpp"
#include "../leetcode-cc/FindPeakElement.hpp"
#include "../leetcode-cc/FindPlayersWithZeroOrOneLosses.hpp"
#include "../leetcode-cc/FlattenBTreeToLinkedList.hpp"
#include "../leetcode-cc/FourSum.hpp"
Expand Down Expand Up @@ -693,5 +694,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SIntersectionOfTwoLL>(); });

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

return 0;
}
Loading