LeetCode162. Find Peak Element

原创 2016年06月01日 10:37:03

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.

这道题要求在O (lgn)的复杂度下找peak值,肯定不能使用遍历,遍历是O(n)。那么可以使用二分法。因为数组两边是无穷小,那么数组里面一定存在peak值。只要我们划分空间即可。

    static  int findPeakElementImp(int[] array, int s , int e){
        if(e-s <= 1){
           return array[e]> array[s]?e:s;
        }
        int mid = s+ (e-s)/2;
        if(array[mid] > array[mid -1] && array[mid]> array[mid+1]){
            return  mid;
        }
        if( array[mid] > array[mid+1]){
            return findPeakElementImp(array ,s, mid);
        }else{
            return  findPeakElementImp(array, mid ,e);
        }
    }
    static  public  void main(String[] args ){
        int[] testArray ={1,2,6};
        int result = findPeakElementImp(testArray, 0, testArray.length -1 );
        System.out.println(result);
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

<LeetCode OJ> 162. Find Peak Element

162. Find Peak ElementMy SubmissionsQuestion Total Accepted: 56981 Total Submissions: 174002 Difficu...

Leetcode 162 Find Peak Element 查找峰值元素(极大值)

给出一个不含重复元素的数组num,找出其中的峰值元素(极大值)并返回其索引(下标)值.

LeetCode - 162. Find Peak Element

题目中给出了一个很重要的假设,就是数组左侧左边和右侧右边的数都是负无穷大,所以我们可以采用一个很方便的算法进行计算。 我们从index为1的时候开始扫描整个数组,比较nums[i]和nums[i -...

【LeetCode】 162. Find Peak Element

162. Find Peak Element介绍

LeetCode 162. Find Peak Element

LeetCode 162. Find Peak Element 两种办法

LeetCode(162) Find Peak Element

题目如下: A peak element is an element that is greater than its neighbors. Given an input array where nu...

【leetcode】162. Find Peak Element

Difficulty:medium A peak element is an element that is greater than its neighbors. Given...

Find Peak Element - LeetCode 162

题目描述: A peak element is an element that is greater than its neighbors. Given an input array where nu...

[LeetCode]162.Find Peak Element

【题目】 A peak element is an element that is greater than its neighbors. Given an input array where ...

LeetCode(162) Find Peak Element

题目A peak element is an element that is greater than its neighbors.Given an input array where num[i] ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)