[leedcode 162] 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.

click to show spoilers.

public class Solution {
    public int findPeakElement(int[] nums) {
        //利用抛物线的知识,因为nums[-1]=nums[n]=-∞,所以抛物线存在极值点
        //传统的办法时间复杂度O(n),二分法时间复杂度O(lgn)
        //分别就mid处在极值点左边还是右边进行分开处理,注意递归的终止条件——是只剩两个点
        if(nums==null||nums.length<=0) return -1;
        int res=find(nums,0,nums.length-1);
        return res;
    }
    public int find(int[] nums,int start,int end){
        if(end-start<=1){
            return nums[start]>nums[end]?start:end;
        }
        int mid=(start+end)/2;
        if(nums[mid]>nums[mid+1]&&nums[mid]>nums[mid-1])return mid;
        if(nums[mid]<nums[mid+1]) return find(nums,mid+1,end);
        if(nums[mid]>nums[mid+1]) return find(nums,start,mid-1);
        return -1;
    }
}

 

posted @ 2015-08-02 11:20  ~每天进步一点点~  阅读(125)  评论(0编辑  收藏  举报