Skip to content

Commit

Permalink
Find peak element (#194)
Browse files Browse the repository at this point in the history
* add find peak element

* impl find peak element
  • Loading branch information
SKTT1Ryze authored Mar 7, 2024
1 parent 31f394a commit 0524d1e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
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;
}

0 comments on commit 0524d1e

Please sign in to comment.