#include <iostream>
#include <vector>
using namespace std;
/*
A peak element is an element that is greater than its neighbors.
Given an input array where nums[i] != nums[i+1], find a peak element
and return its index.
The array may contains muitiple peaks, in that case return the index to
any one of the peaks is fine.
For example:
Given [1, 2, 3, 1], 3 is a peak element and your function should return
the index number 2.
*/
int findPeakElement(vector<int>& nums) {
if(nums.size() == 0) return -1;
int n = nums.size();
if(n == 1) return 0;
int left = 0, right = n - 1;
int mid = 0;
while(left < right) {
int mid = (left + right) / 2;
if((mid == 0 || nums[mid] > nums[mid - 1]) && (mid == n - 1 || nums[mid] >= nums[mid + 1])) return mid;
else if(mid > 0 && nums[mid - 1] > nums[mid]) right = mid - 1;
else left = mid + 1;
}
return mid;
}
int main(void) {
vector<int> nums{4, 2, 1, 1};
cout << findPeakElement(nums) << endl;
}
LeetCode 162. Find Peak Element
最新推荐文章于 2025-05-20 17:29:58 发布