Sunday, November 1, 2015

Zenefits: Find the Peak Element

http://buttercola.blogspot.com/2015/08/leetcode-find-peak-element.html

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.
Understand the problem:
The neighbor of an element A[i] is defined as A[i - 1] and A[i + 1]. Therefore, the peak element is iff A[i] > A[i - 1] && A[i] > A[i + 1]. 

The brute-force solution is quite easy. Just scan and compare. So the time complexity would be O(N). 

However, as is required by the question, the solution should be in O(logn) time. We therefore must think of binary search. 

The idea is: 
  -- If the middle of the array is the peak element, then just return the index. 
  -- If the left neighbor is greater than the middle, move to the left. The peak element must exist in the left half. That is because the num[-1] = num[n] = -inf. 
  -- The same, if the right neighbor is greater than the middle, move to the right. 

Be careful to handle the boundary. Use the binary search template. 


Code (Java):
import java.util.*;
public class Solution {
    public static int findPeakElement(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int lo = 0;
        int hi = nums.length - 1;
        
        while (lo + 1 < hi) {
            int mid = lo + (hi - lo) / 2;
            
            if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
                return nums[mid];
            } else if (nums[mid] < nums[mid - 1]) {
                hi = mid - 1;
            } else if (nums[mid] < nums[mid + 1]) {
                lo = mid + 1;
            }
        }
        
        if (nums[lo] > nums[hi]) {
            return nums[lo];
        } else {
            return nums[hi];
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        
        int[] nums = new int[n];
        
        for (int i = 0; i < n; i++) {
            nums[i] = scanner.nextInt();
        }
        
        int result = Solution.findPeakElement(nums);
        
        System.out.println(result);
        
        scanner.close();
    }
}

No comments:

Post a Comment