码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 162 Find Peak Element

时间:2015-06-05 19:12:17      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

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.

Note:

Your solution should be in logarithmic complexity.

 

解题思路:

题目的提示中要求用log(n)的时间复杂度,因此,只能采用分治的思路,类似归并排序,JAVA实现如下:

    public int findPeakElement(int[] nums) {
        if(nums.length==1||nums[0]>nums[1])
        	return 0;
        if(nums[nums.length-1]>nums[nums.length-2])
        	return nums.length-1;
        int left=1,right=nums.length-2,mid=(left+right)/2;
        if(findPeakElement(nums,mid,right)==-1)
        	return findPeakElement(nums,left,mid);
        return findPeakElement(nums,mid,right);
    }
    static public int findPeakElement(int[] nums,int left,int right) {
    	if(left==right){
    		if(nums[left]>nums[left-1]&&nums[left]>nums[left+1])
    			return left;
    		return -1;
    	}
    	else if(left==right-1){
    		if(nums[left]>nums[left-1]&&nums[left]>nums[left+1])
    			return left;
    		else if(nums[right]>nums[right-1]&&nums[right]>nums[right+1])
    			return right;
    		return -1;
    	}
    	int mid=(left+right)/2;
    	if(findPeakElement(nums,mid+1,right)==-1)
        	return findPeakElement(nums,left,mid);
        return findPeakElement(nums,mid+1,right);
    }

 

Java for LeetCode 162 Find Peak Element

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4555242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!