Find Peak Element

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

 

你可能感兴趣的:(element)