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.

一个峰值元素是大于其相邻元素的元素.给出一个不含重复元素的数组num,找出其中的峰值元素并返回其索引(下标)值.这个数组可能含有多个峰值元素,在这种情况下返回任意一个峰值元素的下标都可以.

思路:使用双指针,

如果 mid1大于 mid2,应该看mid1左边的值是否小于mid1

如果 mid1小于等于 mid2,应该看mid2右边的值是否小于mid2

 1     public int findPeakElement(int[] nums) {
 2       int left = 0,right = nums.length-1;
 3       while (left < right)
 4       {
 5           int mid1 = (left+right)/2;
 6           int mid2 = mid1+1;
 7           if (nums[mid1]>nums[mid2]) right = mid1;
 8           else left =mid2;
 9       }
10       return left;        
11     }
原文地址:https://www.cnblogs.com/wzj4858/p/7677421.html