Merge branch '12_find_peak_element'

This commit is contained in:
Manish 2023-03-12 18:35:59 +11:00
commit c6c1b85f6c

53
12_find_peak_element.cpp Normal file
View File

@ -0,0 +1,53 @@
/* Problem: https://leetcode.com/problems/find-peak-element/
*/
#include <iostream>
#include <vector>
int solution(const std::vector<int> &nums) {
if (nums.size() == 0) {
return -1;
}
if (nums.size() == 1) {
return 0;
};
long long first = 0, last = nums.size() - 1, pi = last / 2;
while (true) {
if (pi == 0) {
if (nums[pi] > nums[pi + 1]) {
return pi;
} else {
first = pi + 1;
pi = ((last - first) / 2) + first;
continue;
}
} else if (pi == (long long)nums.size() - 1) {
if (nums[pi] > nums[pi - 1]) {
return pi;
} else {
last = pi - 1;
pi = ((last - first) / 2) + first;
continue;
}
}
if (nums[pi] < nums[pi - 1]) {
last = pi - 1;
} else if (nums[pi] < nums[pi + 1]) {
first = pi + 1;
} else {
return pi;
}
pi = ((last - first) / 2) + first;
}
return pi;
}
int main() {
std::vector<int> nums1 = {1, 2, 3, 1}, nums2 = {1, 2, 1, 3, 5, 6, 4};
int i1, i2;
i1 = solution(nums1);
std::cout << i1 << " : " << nums1[i1] << '\n';
i2 = solution(nums2);
std::cout << i2 << " : " << nums2[i2] << '\n';
}