C# solution: binary search, check mid-1 & mid+1 to determine the peak


  • 0
    B
    public class Solution {
        public int FindPeakElement(int[] nums) 
        {
            var n = nums.Length;
    
            if (n == 0) return -1;
            if (n == 1) return 0;
    
            var left = 0;
            var right = n - 1;
    
            while(left < right)
            {
                var mid = left + (right - left) / 2;
    
                if (mid - 1 >= 0 && mid + 1 < n && nums[mid-1] < nums[mid] && nums[mid] > nums[mid+1])
                {
                    return mid;
                }
                else if ((mid - 1 >= 0 && nums[mid-1] < nums[mid]) || (nums[mid] < nums[mid + 1]))
                {
                    left = mid + 1;
                }
                else
                {
                    right = mid;
                }
            }
    
            return left;
        }
    }
    

Log in to reply
 

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