LeetCode 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.

Note:

Your solution should be in logarithmic complexity.

 


题目标签:Array, Binary Search

 

  题目给了我们一个array,让我们找到任意一个峰值,而且肯定有至少一个峰值存在。既然题目说了要用O(logn),那么就要用二分法了。
  利用二分法是为了,比较中间的值,和其他值,来判定,要去左半边还是右半边继续搜索。那么如何来判断峰值在哪里呢?
  这里有4种情况来判断峰值在哪儿?
  1. nums[mid-1] < nums[mid] > nums[mid+1]  这种情况是中间最高,两边都低,那么中间的已经是一个峰值了,直接返回index 就可以;
  2. nums[mid-1] < nums[mid] < nums[mid+1]  这种是递增趋势,那么峰值一定会在mid 的右边,缩小到右半边;
  3. nums[mid-1] > nums[mid] > nums[mid+1]  这种是递减趋势,那么峰值一定会在mid 的左边,缩小到左半边;
  4. nums[mid-1] > nums[mid] < nums[mid+1]  这种情况是中间低,两边都高,那么两边都会有峰值,去任意一边搜索。
 
  直到只有两个数字或者一个数字的时候,返回大的那一个数字的index就可以。
 
 

Java Solution:

Runtime beats 31.71% 

完成日期:08/31/2017

关键词:Array, Binary search, 

关键点:4种可能性来判断峰值的位置

 

 1 class Solution 
 2 {
 3     public int findPeakElement(int[] nums) 
 4     {
 5         int left = 0;
 6         int right = nums.length -1;
 7         
 8         while(left < right - 1)
 9         {
10             int mid = left + (right - left) / 2;
11             // if find peak number
12             if(nums[mid-1] < nums[mid] && nums[mid] > nums[mid+1])
13                 return mid;
14             else if(nums[mid-1] < nums[mid] && nums[mid] < nums[mid+1]) 
15             { // if find ascending three numbers, the peak number must be in [mid+1, n-1]
16                 left = mid + 1;                
17             }
18             else if(nums[mid-1] > nums[mid] && nums[mid] > nums[mid+1])
19             { // if find descending three numbers, the peak number must be in [0, mid-1]
20                 right = mid - 1;
21             }
22             else if(nums[mid-1] > nums[mid] && nums[mid] < nums[mid+1])
23             { // if find the mid number is smaller than both neighbors, meaning both sides have peak number
24                 right = mid - 1;
25             }
26         }
27         
28         return nums[left] > nums[right]? left:right;
29     }
30 }

参考资料:

https://discuss.leetcode.com/topic/5848/o-logn-solution-javacode/14

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-09-01 07:13  Jimmy_Cheng  阅读(312)  评论(0编辑  收藏  举报