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