liuxuhelloworld's notebook

题目链接

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

解答过程

这个题目的关键是二分后如何舍弃某一半:

	public int findPeakElement(int[] nums) {
		int len = nums.length;
		if (len == 1) {
			return 0;
		}

		int left = 0, right = len - 1;
		while (left <= right) {
			int mid = left + (right - left) / 2;
			if (isPeak(nums, mid)) {
				return mid;
			} else if (nums[mid] < nums[mid+1]) {
				left = mid + 1;
			} else {
				right = mid - 1;
			}
		}

		return -1; // logically unreachable statement
	}

	private boolean isPeak(int[] nums, int i) {
		int len = nums.length;
		if (len == 1) {
			return true;
		}

		if (i == 0) {
			return nums[i] > nums[i+1];
		}

		if (i == len - 1) {
			return nums[i] > nums[i-1];
		}

		return nums[i] > nums[i-1] && nums[i] > nums[i+1];
	}

看了下官方题解,思路是差不多的,但我觉得我的代码更好理解。