C# easy to understand


  • 0
    M
    public class Solution {
        public int FindPeakElement(int[] nums) {
            if(nums ==null || nums.Length ==0) return 0;
            
            // handle 1 element
            if(nums.Length ==1) return 0;
            // handle 2 elements
            if(nums.Length ==2) return nums[0]<nums[1]?1:0;
            
            for(int i=0; i<nums.Length-2; i++)// handle 3+ elements
            {
                //if peak in the center 
                if(nums[i]<nums[i+1] && nums[i+1]>nums[i+2]) return i+1;
            }
            
            // Not found, peak is either the first or last 
            return nums[0]<nums[nums.Length-1]?nums.Length-1:0;element
        }
    }

Log in to reply
 

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