Find Peak Element

LeetCode Q 162 - Find Peak Element

A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.

Solution

Code:

public int findPeakElement(int[] nums) {
	if (nums.length == 1) return 0;
	int left = 0, right = nums.length - 1;
	while (left <= right) {
		int mid = (left + right) / 2;
		if (nums[mid] > nums[mid + 1]) 
			right = mid;
		else 
			left = mid + 1;
	}
	return left;
}

   Reprint policy


《Find Peak Element》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC