|
| 1 | +package binary_search; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 10/07/2017. |
| 5 | + * A peak element is an element that is greater than its neighbors. |
| 6 | +
|
| 7 | + Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. |
| 8 | +
|
| 9 | + The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. |
| 10 | +
|
| 11 | + You may imagine that num[-1] = num[n] = -∞. |
| 12 | +
|
| 13 | + For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. |
| 14 | +
|
| 15 | + Note: |
| 16 | + Your solution should be in logarithmic complexity. |
| 17 | +
|
| 18 | + Solution: O(log N) check if the first or the last element is the peak element, if yes then return this index. |
| 19 | + Else binary search for the answer - check mid element if this is a peak element return this index, else if the |
| 20 | + left element is greater than current element search left else search right. |
| 21 | + */ |
| 22 | +public class FindPeakElement { |
| 23 | + public static void main(String[] args) throws Exception{ |
| 24 | + int[] nums = {3, 4, 3, 2, 1}; |
| 25 | + System.out.println(new FindPeakElement().findPeakElement(nums)); |
| 26 | + } |
| 27 | + |
| 28 | + public int findPeakElement(int[] nums) { |
| 29 | + if(nums.length == 1)return 0; |
| 30 | + if(nums[0] > nums[1]) |
| 31 | + return 0; |
| 32 | + else if(nums[nums.length - 1] > nums[nums.length - 2]) |
| 33 | + return nums.length - 1; |
| 34 | + |
| 35 | + int l = 0, h = nums.length - 1; |
| 36 | + int ans = 0; |
| 37 | + while(l <= h){ |
| 38 | + int m = l + (h - l) / 2; |
| 39 | + if(m - 1 >= 0 && m + 1 < nums.length){ |
| 40 | + if(nums[m] > nums[m - 1] && nums[m] > nums[m + 1]){ |
| 41 | + return m; |
| 42 | + } |
| 43 | + } |
| 44 | + if(m - 1 >= 0 && nums[m - 1] > nums[m]){ //search left |
| 45 | + h = m - 1; |
| 46 | + } |
| 47 | + else { |
| 48 | + ans = l; //mark this as the answer and search right |
| 49 | + l = m + 1; |
| 50 | + } |
| 51 | + } |
| 52 | + return ans; |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments