A more general solution for finding ALL peak indices


  • 0
    Z

    public int findPeakElement(int[] nums) {

        if(nums.length==1)return 0;
        
        List<Integer> peaks = new ArrayList<Integer>();
        
        findPeak(0,nums.length,nums,peaks);
        
        return peaks.get(0);
        
    }
    
    
    public void findPeak(int start,int end,int[] nums,List<Integer> peaks){
        if(start>end || start==nums.length || end<0)return ;
        
        int middle = start+(end-start)/2;
        
        if(middle==0){
            if(nums[start]>nums[start+1]){
                peaks.add(0);
            }
            else{
                findPeak(1,1,nums,peaks);
            }
        }else if(middle==nums.length-1){
            if(nums[middle]>nums[middle-1]){
                peaks.add(middle);
            }
        }else{
          if(nums[middle]>nums[middle-1] && nums[middle]>nums[middle+1]){
            peaks.add(middle);
          }
        }
        
        findPeak(middle+1,end,nums,peaks);
        findPeak(start,middle-1,nums,peaks);
    }

Log in to reply
 

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