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.
Note:
Your solution should be in logarithmic complexity.
[Thoughts]
是个简单的遍历题,注意边界的处理。这里在两边各加了个最小值,可以简化逻辑。
[Code]
1: int findPeakElement(vector<int>& nums) {
2: if(nums.size() <= 1) {
3: return nums.size()-1;
4: }
5:
6: nums.insert(nums.begin(), INT_MIN);
7: nums.push_back(INT_MIN);
8:
9: int len = nums.size();
10: int p = 1;
11: for(; p<len; p++) {
12: if(nums[p]>nums[p-1] && nums[p]>nums[p+1]) {
13: break;
14: }
15: }
16:
17: return p-1;
18: }
No comments:
Post a Comment