A peak element is an element, which 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 be contain multiple peaks, in this case return the index to any one of the peaks is fine.
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.
Click to show spoilers.
Analysis:
- If there is only one element, return 0 directly;
- If the number of elements >=2, determine whether the end is greater than its nearby elements, greater than the return subscript;
- Loop traversal, subscript from >=1 to < n-1, determine whether Nums[i] is at the same time greater than its nearby elements, if greater than the return of the subscript;
Otherwise, return-1;
Code (c + +)
classSolution { Public:intFindpeakelement ( vector<int>& Nums) {intn = nums.size ();if(n==1)return 0;if(nums[0] > nums[1])return 0;if(nums[n-1] > nums[n-2])returnN-1; for(intI=1; i<n-1; i++) {if(nums[i]>nums[i-1] && nums[i]>nums[i+1]){returnI } }return-1; }};
Leetcode[162]-find Peak Element