码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Find Peak Element

时间:2014-12-23 17:29:15      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:leetcode   递归   数组   peak   java   

一原题

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]<num[mid-1],则在num[start..mid-1]中存在至少一个最大值点;

(3)num[mid]<num[mid+1],则在num[mid+1..end]中存在至少一个最大值点;

对于(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]<num[mid-1])
			 mid=recusiveFind(num,start,mid-1);
		 else if(num[mid]<num[mid+1])
			mid= recusiveFind(num,mid+1,end);
		 return mid;
	 }
}


【Leetcode】Find Peak Element

标签:leetcode   递归   数组   peak   java   

原文地址:http://blog.csdn.net/dr_titi/article/details/42103377

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!