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.
Your solution should be in logarithmic complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题目解析:
因为要求logarithmic complexity, 所以一看就是用二分的思想来做. 两个mid index
1 public int findPeakElement(int[] num) { 2 int start = 0; 3 int end = num.length - 1; 4 while(start != end){ 5 int mid1 = start + (end - start) / 2; 6 int mid2 = mid1 + 1; 7 if(num[mid1] < num[mid2]){ 8 start = mid2; 9 }else 10 end = mid1; 11 } 12 return start; 13 }
Leetcode 162 Find Peak Element (二分查找思想)
原文:http://www.cnblogs.com/sherry900105/p/4294568.html