C# binary search approach with recursion - easy to understand


  • 0
    J
    public class Solution {
    public int FindPeakElement(int[] nums) {
        if(nums==null || nums.Length==0) { return -1; }
        return FindPeakElement_Impl(nums, 0, nums.Length-1);
    }
    
    private int FindPeakElement_Impl(int[] nums, int p, int r)
    {
        int m=(p+r)/2;
        int n=nums.Length;
        if(m+1<=n-1 && nums[m+1]>nums[m])
        { return FindPeakElement_Impl(nums, m+1, r); }
        if(m-1>=0 && nums[m-1]>nums[m])
        { return FindPeakElement_Impl(nums, p, m-1); }
        
        return m;
    } }

Log in to reply
 

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