162. Find Peak Element

202406291446
tags: #binary-search

var findPeakElement = function(nums) {
	const n = nums.length;
	if (n === 1) {
		return 0;
	}
	if (nums[0] > nums[1]) {
		return 0;
	}
	if (nums[n - 1] > nums[n - 2]) {
		return n - 1;
	}
	let start = 1;
	let end = n - 2;
	while (start <= end) {
		const mid = Math.floor((end - start) / 2) + start;
		if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
			return mid;
		}
		else if (nums[mid] < nums[mid - 1]) {
			end = mid - 1;
		}
		else if (nums[mid] < nums[mid + 1]) {
			start = mid + 1;
		}
	}
	return -1;
};

Reference

https://leetcode.com/problems/find-peak-element/