Two Solutions


  • 0
    5

    public class Solution {
    public int findPeakElement(int[] nums) {
    // Solution 1:
    // if(nums==null){
    // return -1;
    // }
    // if(nums.length==1){
    // return 0;
    // }
    // if(nums.length==2){
    // if(nums[0]>nums[1]){
    // return 0;
    // }
    // else {
    // return 1;
    // }
    // }
    // if(nums[0]>nums[1]){
    // return 0;
    // }
    // for(int i=1;i<nums.length-1;i++){
    // if(nums[i]>nums[i-1] && nums[i]>nums[i+1]){
    // return i;
    // }
    // }
    // if(nums[nums.length-1]>nums[nums.length-2]){
    // return nums.length-1;
    // }
    // return -1;

        // Solution 2:
        if(nums==null || nums.length==0){
            return -1;
        }
        int start=0;
        int end=nums.length-1;
        while(start+1<end){
            int mid=start+(end-start)/2;
            if(nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1]){
                return mid;
            }
            if(nums[mid]>nums[mid-1]){
                start=mid;
            }
            if(nums[mid]>nums[mid+1]){
                end=mid;
            }
            else{
                start=mid;
            }
        }
        if(nums[start]>=nums[end]){
            return start;
        }
        else{
            return end;
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.