Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array where
num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that
num[-1] = num[n] = -∞
.
For example, in array
[1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
-------------------------------------- thinking -----------------------------------------------------------------------
definitely using divide and conquer!!
What's the edge condition:
1. when the length is 0, 1 and 2
2. when the middle point is at bottom, which is mid < left && mid < right!!! (having a bug here!)
--------------------------------------- problems --------------------------------------------------------------------
I made a mistake on deciding which direction to go!
--------------------------------------- codes -------------------------------------------------------------------------
class Solution {
public:
int findPeakElement(const vector<int> &num) {
int len = num.size();
int lft = 0;
int rit = len - 1;
if (len == 1) {
return 0;
}
//while (lft < rit && lft >= 0 && rit < len) {
while (lft < rit) {
int mid = floor((lft + rit) / 2.0);
int mid_left = mid >= 1?num[mid-1]:num[mid] - 1;
int mid_right = mid <= len - 2?num[mid+1]:num[mid] - 1;
if (num[mid] > mid_left && num[mid] > mid_right) {
return mid;
} else if (num[mid] < mid_left && mid >= 1) {//bug here, be clear about which direction we should go
rit = mid - 1;
} else if (num[mid] <mid_right && mid < len - 1) {
lft = mid + 1;
}
}
return lft;
}
};
No comments:
Post a Comment