A simple solution that doesn't use recursion


  • -1
    S

    This solution doesn't involve recursion. It's easy to understand, although the complexity is higher than recursive method.

    public class Solution {
        public int findPeakElement(int[] nums) {
            if (nums.length == 1) return 0;
            if (nums.length == 2) return nums[0] > nums[1] ? 0:1; 
            int i = 1; 
            for (; i < nums.length-1; i++) {
                if (nums[i] > Math.max(nums[i-1], nums[i+1]) )
                    return i; 
            }
            return nums[0]>nums[i]?0:i; 
        }
    }

Log in to reply
 

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