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.

答案

class Solution {
    public int findPeakElement(int[] nums) {
        int l = 0, r = nums.length - 1;
        int lnum, rnum;
        while(l < r) {
            int m = l + (r - l) / 2;
            lnum = (m == 0) ? Integer.MIN_VALUE : nums[m - 1];
            rnum = (m == nums.length - 1) ? Integer.MIN_VALUE : nums[m + 1];

            if(nums[m] > lnum && nums[m] > rnum) return m;
            if(rnum > nums[m]) l = m + 1;
            else r = m;
        }
        return l;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,504评论 0 10
  • A peak element is an element that is greater than its nei...
    ShutLove阅读 194评论 0 0
  • A peak element is an element that is greater than its nei...
    matrxyz阅读 244评论 0 0
  • 01 怎么使用听力材料 L3学习的流程:每天3个环节。单词→情景→听力,做完听力的3道题,提交答案到查看解析的页面...
    朵朵西里阅读 347评论 0 0
  • 彩铅,西红柿。画完之后感觉阴影的位置不太对,偏右会更好一些。 只因喜爱,所以坚持。我建了一个画画打卡群,欢迎喜欢画...
    山水奏鸣阅读 234评论 0 2