My JAVA solution


  • 0
    Q
    public class Solution {
        public int findPeakElement(int[] nums) {
             if (nums.length  == 1){
    	          return 0;
    	      }
    	      return findPeak(nums, 0, nums.length-1, nums.length/2);
        }
        
        private int findPeak(int[] nums, int startIndex, int endIndex, int index){
            if (startIndex == endIndex){
               return startIndex;
           }
           if (startIndex+1 == endIndex){
               if (nums[startIndex] > nums[endIndex]){
            	   return startIndex;
               }
               return endIndex;
           }
           if (index == 0 && nums[index] > nums[index+1]){
               return index;
           }
           if (index == nums.length-1 && nums[index] > nums[index-1]){
               return index;
           }
           if (nums[index]>nums[index-1] && nums[index]>nums[index+1]){
               return index;
           }
           
           if (nums[index] > nums[index+1]){
               return findPeak(nums, startIndex, index, (startIndex+index)/2);
           }
           return findPeak(nums, index, endIndex, (index+endIndex)/2);
        }
    }

  • 0
    R

    Why if (nums[index] > nums[index+1]) then you are going for left half otherwise right half?


  • 0
    Q

    If nums[index] > nums[index+1] I do binary search on left half otherwise on right half.


Log in to reply
 

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