Find Peak Element

来源:互联网 发布:淘宝户外用品店那家好 编辑:程序博客网 时间:2024/04/30 02:53

Q:

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.


Solution:

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


0 0
原创粉丝点击