Thursday, December 11, 2014

Find Peak Element

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.
I found the bug in my code now it's accepted!


public class FindPeak {
    public int findPeakElement(int[] num) {
      if (num == null || num.length == 0)
            return -1;
        int start = 0;
        int end = num.length - 1;
        while (start + 1 < end)
        {
            int mid = (start + end) / 2;
            if (num[mid] > num[mid - 1] && num[mid] > num [mid + 1])
                return mid;
            else if (num[mid] < num[mid - 1])
                end = mid - 1;
            else if (num[mid] < num[mid + 1])
                start = mid + 1;
        }
        if (num[start] > num[end])
            return start;
        return end;
    }
}

Ah, still warm problem! Since the problem requires log(n) complexity, binary search comes to my mind. Start from the middle element, if middle element is the peak, return it! Otherwise if num[mid] is less than num[mid - 1], go to the left part, else, go to the right part.


The complier on LeetCode is giving me an ArrayIndexOutOfBoundsException, which I could not figure out the reason. On the other hand, my Eclipse compiles it perfectly fine.... Weird...

public class FindPeak {
    public int findPeakElement(int[] num) {
      if (num == null || num.length == 0)
            return -1;
        int start = 0;
        int end = num.length - 1;
        while (start < end)
        {
            int mid = (start + end) / 2;
            if (num[mid] > num[mid - 1] && num[mid] > num [mid + 1])
                return mid;
            else if (num[mid] < num[mid - 1])
                end = mid;
            else 
                start = mid;
        }
        return start;
    }
}

No comments:

Post a Comment