2015年3月23日星期一

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.


Credits:
Special thanks to @ts for adding this problem and creating all test cases.


public class Solution {
    public int findPeakElement(int[] num) {
        int s = 0;
        int e = num.length;
        while(s<=e) {
            int m = (s+e)/2;
           
            if((m==0 || num[m]>num[m-1]) && (m==num.length-1 || num[m]>num[m+1])) {
                return m;
            } else if((m==0 || num[m]>num[m-1]) && (m!=num.length-1 && num[m]<num[m+1])) {
                s = m + 1;
            } else {
                e = m - 1;
            }
        }
        return -1;
    }
}

没有评论:

发表评论