首页 > 其他 > 详细

Leetcode 162 Find Peak Element (二分查找思想)

时间:2015-02-16 23:27:17      阅读:427      评论:0      收藏:0      [点我收藏+]

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.

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!