Thursday, August 6, 2015

Find Peak Element | Leetcode

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

 
Note: Your solution should be in logarithmic complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

---

Solution: Iterate through the array. If the current element is greater than the left and right elements, then it is a peak element. Return its index (not its value) as the answer.

We will definitely have an answer, so return the last index if none of the previous elements were peak elements.
public class Solution {
    public int findPeakElement(int[] nums) {
        int last = nums.length - 1;

        for (int i = 0; i < last; i++) {
            boolean greaterThanLeft = (i == 0) || (nums[i] > nums[i - 1]);
            boolean greaterThanRight = (i == last) || (nums[i] > nums[i + 1]);
            
            if (greaterThanLeft && greaterThanRight) {
                return i;
            }
        }

        // Last element must be a peak element if we did not find anything else.
        return last;
    }
}

No comments: