lintcode : find peak element 寻找峰值

题目

寻找峰值

你给出一个整数数组(size为n),其具有以下特点:

  • 相邻位置的数字是不同的
  • A[0] < A[1] 并且 A[n - 2] > A[n - 1]

假定P是峰值的位置则满足A[P] > A[P-1]A[P] > A[P+1],返回数组中任意一个峰值的位置。

样例

给出数组[1, 2, 1, 3, 4, 5, 7, 6]返回1, 即数值 2 所在位置, 或者6, 即数值 7 所在位置.

注意

数组可能包含多个峰值,只需找到其中的任何一个即可

解题

直接遍历

Java

class Solution {
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    public int findPeak(int[] A) {
        // write your code here
        if(A == null || A.length == 0)
            return -1;
        if(A.length == 1)
            return 0;
        for(int i=1;i<A.length-1; i++){
            if(A[i] >A[i-1] && A[i] >A[i+1])
                return i;
        }
       if(A[0]>A[1])
            return 0;
        if(A[A.length-1] >A[A.length - 1])
            return A.length - 1;
        return -1;
    }

}

Python

class Solution:
    #@param A: An integers list.
    #@return: return any of peek positions.
    def findPeak(self, A):
        # write your code here
        if A == None or len(A) ==0:
            return -1
        for i in range(1,len(A)-1):
            if A[i]>A[i-1] and A[i]>A[i+1]:
                return i
        if A[0]>A[1]:
            return 0
        if A[len(A)-1] >A[len(A)-2]:
            return len(A)-1
        return -1
原文地址:https://www.cnblogs.com/theskulls/p/5113705.html