[LeetCode] 162. 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.

Thought process:
O(n) solution is trivial. The spoiler says that our solution should be in log complexity. Binary search is a natural choice. 
After we find the middle element, there could be four cases:
  1. nums[mid] < nums[mid - 1] && nums[mid] < nums[mid + 1]: we found a bottom. We can go either to the left or right.
  2. nums[mid] < nums[mid - 1] && nums[mid] > nums[mid + 1]: we found a point on a down trend. We should go left.
  3. nums[mid] > nums[mid - 1] && nums[mid] < nums[mid + 1]: we found a point on an up trend. We should go right.
  4. nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]: we found a peak.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
    public int findPeakElement(int[] nums) {
        if (nums.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = nums.length - 1;
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            
            if (nums[mid] < nums[mid - 1]) {
                end = mid;
            } else if (nums[mid] < nums[mid + 1]) {
                start = mid;
            } else {
                return mid;
            }
        }
        
        if (nums[start] < nums[end]) {
            return end;
        } else {
            return start;
        }
    }
}

Time complexity: O(logn).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula