首页 > 其他 > 详细

Find Peak Element

时间:2015-04-19 14:32:14      阅读:117      评论:0      收藏:0      [点我收藏+]
public class Solution {
    public int findPeakElement(int[] num) {
        // binary search http://siddontang.gitbooks.io/leetcode-solution/content/array/find_peak_element.html
        
        if(num==null || num.length ==0) return -1;
        if (num.length==1)
            return 0;
        int left=0, right=num.length-1;
        int mid=left+(right-left)/2;
        
        while(left<= right){
            mid=left+(right-left)/2;
             
            //if(mid == 0 || num[mid]>=num[mid-1] &&num[mid]>=num[mid+1] || mid == num.length-1 ) return mid;
            // if((mid == 0 || num[mid]>=num[mid-1] ) && (num[mid]>=num[mid+1] || mid == num.length-1) ) return mid; // java 里不能存在不存在的index 索引吧,比如num[-1]
            
            if((mid==0 && num[mid]>num[mid+1]) || (mid==num.length-1 && num[mid] > num[mid-1]) || ( num[mid]>num[mid+1] && num[mid] > num[mid-1])) return mid;
            
            if(mid>0 && num[mid]<num[mid-1]){
                right = mid-1;
            }else 
                left = mid+1;
            
        }
        
        return mid;
        
    }
}

leetcode 把输入的int[]改为list,非常不好用,只好贴一些之前的code

 

Find Peak Element

原文:http://www.cnblogs.com/jiajiaxingxing/p/4438970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!