【Leetcode】Find Peak Element

一原题

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.

Note:

Your solution should be in logarithmic complexity.


二分析

时间复杂度要求是O(lgn),而且不要求找到全部极大值点,可以使用二分查找,递归的求解这个问题。对num[start...end],令mid=(start+end)/2,如果:

(1)num[mid]>num[mid-1]&&num[mid]>num[mid+1],返回mid;

(2)num[mid]

(3)num[mid]

对于(2)(3)两种情况,解释如下(以(2)为例):

若num[start..mid-1]是有序的,则num[start]或num[mid-1]是最大值;

若num[start..mid-1]是无序的,而且每个相邻元素都不想等,则一定会有最大值点存在

三代码(java)

public class Solution {
  public int findPeakElement(int[] num) {
	        return recusiveFind(num,0,num.length-1);
	    }
	 public int recusiveFind(int[] num,int start,int end){
		 if(end-start==1)
			 return (num[start]>num[end])?start:end;//只剩下两个元素的时候,必有一个是最大值
		 if(start==end)
			 return start;
		 int mid=(start+end)/2;
		 if(num[mid]>num[mid-1]&&num[mid]>num[mid+1])
			 return mid;
		 else if(num[mid]


你可能感兴趣的:(leetcode)