1ms Accepted Java solution with 13 lines of code


  • 0
    S

    Solution: if there's only one element in the array, return that index.
    There are 3 cases:
    1. [1,2] return index 0 (first if condition)
    2. [2,1] return index 0 (second if condition)
    3. [1,3,2,1] return 1 (last if condition)

    Code:

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

  • 0

    but it seems not the logarithmic scale...


Log in to reply
 

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