LeetCode 852. Peak Index in a Mountain Array (山脉数组的峰顶索引)
题目标签:Binary Search
题目给了我们一组 int array,让我们找到数组的 peak。
利用 binary search, 如果数字比它后面那个数字小,说明还在上坡,缩小范围到右半边;
如果一个数字比它后面的大,说明是下坡,或者是peak,缩小范围到左半边,这里要包含mid,因为mid 可能是peak。具体看code。
Java Solution:
Runtime: 0 ms, faster than 100 %
Memory Usage: 39 MB, less than 85 %
完成日期:08/01/2019
关键点:比较相邻的数字来判断
class Solution { public int peakIndexInMountainArray(int[] A) { int left = 0; int right = A.length-1; while(left < right) { int mid = left + (right - left) / 2; if(A[mid] < A[mid + 1]) //up hill left = mid + 1; else // down hill or peak right = mid; } return left; } }
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/