Sharing my C# solution O(logn)


  • -1
    Y
    public class Solution {
        public int FindPeakElement(int[] nums) {
        
        return FindPeakElement(nums,0,nums.Length-1);
      }
    
    public int FindPeakElement(int[] nums,int low, int high) {
        
       if(nums.Length == 1)
    	{
    		return 0;
    	}		
    	
        while (low <= high)
        {      
    		int middle = (low + high)/2;
    		
    		if(middle == 0)
    		{
    		   if(nums[middle]>nums[1])
    		   {   
                return middle;
    		   }
    			else
    			{
    				low = middle+1; continue;
    			}				
    		}
    		
             if(middle == nums.Length-1)
    		{
    		   if(nums[low] > nums[low-1])
    		   {   
                return middle;
    		   }
    			else
    			{
    				high = middle-1; continue;
    			}
    		}
    
                
            if(nums[middle] > nums[middle-1] && nums[middle] > nums[middle+1])
                return middle;
            
            if(nums[middle] > nums[middle-1] && nums[middle]<nums[middle+1])
    		{ low = middle+1; continue;}
                
            if(nums[middle] < nums[middle-1] && nums[middle] > nums[middle+1])
    		{ high = middle-1; continue;}
                
            if(nums[middle] < nums[middle-1] && nums[middle] < nums[middle+1])
            {
    			if(FindPeakElement(nums, low, middle-1) == -1)				
    				return FindPeakElement(nums, middle+1, high);				
    			
                return FindPeakElement(nums, low, middle-1);                
            }
        }
    	
    	
        
        return -1;
      }
     }

Log in to reply
 

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