LeetCode 162. Find Peak Element
原题链接在这里:https://leetcode.com/problems/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.
题解:
二分法, 如何判断接下来应该找左边还是右边呢。依据其实是比较nums[m] 和 nums[m+1], 若是nums[m] < nums[m+1], peak 一定会出现在mid 右边,不包括mid.
反之peak 就会出现在mid 左边, 但要包括mid.
Time Complexity: O(logn). Space: O(1).
AC Java:
1 class Solution { 2 public int findPeakElement(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return -1; 5 } 6 7 int l = 0; 8 int r = nums.length - 1; 9 while(l < r){ 10 int mid = l + (r-l)/2; 11 if(nums[mid] < nums[mid+1]){ 12 l = mid+1; 13 }else{ 14 r = mid; 15 } 16 } 17 18 return r; 19 } 20 }