首页 > 代码库 > 162. Find Peak Element
162. 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.
链接: http://leetcode.com/problems/find-peak-element/
6/15/2017
抄的,没有注意到负无穷是在数组之外
在这道题中,[6,5,4,1,2,0]返回6的下标0而不是2的下标5,即使2是一个更加明显的peak
注意第12,14行的不同。原因:第12行中因为lo可能和mid指向一个位置,所以lo=mid以保证不要遗漏。第14行中因为如果hi = mid - 1的话有可能导致下一步hi < lo而漏过最开始的一个元素(数组第一个元素)
1 public class Solution { 2 public int findPeakElement(int[] nums) { //MIT 6.006 Introduction to Algorithms 3 if(nums == null || nums.length == 0) // watch the 2d version 4 return 0; 5 int lo = 0, hi = nums.length - 1; 6 7 while(lo <= hi) { 8 if(lo == hi) 9 return lo; 10 int mid = lo + (hi - lo) / 2; 11 if(nums[mid] < nums[mid + 1]) 12 lo = mid + 1; 13 else 14 hi = mid; 15 } 16 17 return -1; 18 } 19 }
别人的解法
有follow up
http://www.cnblogs.com/yrbbest/p/4489719.html
更像普通的binary search的解法,因为把lo==hi这部分放在最后和-1一起返回
https://discuss.leetcode.com/topic/7600/a-concise-standard-binary-search-solution
值得借鉴的顺序查找,虽然时间复杂度差一些
https://discuss.leetcode.com/topic/5724/find-the-maximum-by-binary-search-recursion-and-iteration
更多讨论
https://discuss.leetcode.com/category/170/find-peak-element
162. Find Peak Element