Advertisement
vladimirVenkov

Find Peak Element Binary Search

Jul 10th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. /* A peak element is an element that is greater than its neighbors.
  2.  
  3. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
  4.  
  5. The array may contain multiple peaks, in that case, return the index to any one of the peaks is fine.
  6.  
  7. You may imagine that nums[-1] = nums[n] = -∞.
  8.  
  9. Example 1:
  10.  
  11. Input: nums = [1,2,3,1]
  12. Output: 2
  13. Explanation: 3 is a peak element and your function should return the index number 2.
  14. Example 2:
  15.  
  16. Input: nums = [1,2,1,3,5,6,4]
  17. Output: 1 or 5
  18. Explanation: Your function can return either index number 1 where the peak element is 2,
  19.              or index number 5 where the peak element is 6.
  20. Note:
  21.  
  22. Your solution should be in logarithmic complexity.
  23. */
  24.  
  25. class Solution {
  26.     public int findPeakElement(int[] nums) {
  27.         if (nums.length == 0) {
  28.             return -1;
  29.         }
  30.         return findHelper(nums, 0, nums.length - 1);
  31.     }
  32.    
  33.     private int findHelper(int[] nums, int left, int right) {
  34.         if (left > right) return - 1;
  35.        
  36.         int midIndex = left + ((right - left) / 2);
  37.         int mid = nums[midIndex];
  38.         int pre = midIndex == 0 ? Integer.MIN_VALUE : nums[midIndex - 1];
  39.         int post = midIndex == nums.length - 1 ? Integer.MIN_VALUE : nums[midIndex + 1];
  40.        
  41.         if (mid > pre && mid > post || left == right) return midIndex;
  42.        
  43.         else if (mid < pre) return findHelper(nums, left, midIndex - 1);//left side has the peak
  44.        
  45.         else return findHelper(nums, midIndex + 1, right);//right side has the peak
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement