本文主要是介绍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.
click to show spoilers.
Your solution should be in logarithmic complexity.
问题分析:
过程详见代码:
class Solution {
public:int findPeakElement(vector<int>& nums) {int low = 0;int high = nums.size()-1;while(low < high){int mid1 = (low+high)/2;int mid2 = mid1+1;if(nums[mid1] < nums[mid2])low = mid2;elsehigh = mid1;}return low;}};
这篇关于Find Peak Element问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!