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.
package com.vic.leetcode.solutions;
public class Solution {
public int findPeakElement(int[] num) {
if(null==num||num.length==0)
return 0;
return findPeak(num,0,num.length);
}
public int findPeak(int[] num, int start, int end) {
if(start > end)
return -1;
int key = start + (end - start) / 2;
boolean left = false, right = false;
left = key == 0 || num[key] > num[key - 1] ? true : false;
right = key == num.length-1 || num[key] > num[key + 1] ? true : false;
if(left && right)
return key;
int leftKey = findPeak(num, start, key - 1);
if(leftKey==-1)
return findPeak(num, key+1, end);
return leftKey;
}
}