[Java][BinarySearch][LeetCode] Peak Index In A Mountain Array #852

SP Hou
1 min readJan 10, 2022

Let’s call an array arr a mountain if the following properties hold:

  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
  • arr[0] < arr[1] < ... arr[i-1] < arr[i]
  • arr[i] > arr[i+1] > ... > arr[arr.length - 1]

Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

Example 1:

Input: arr = [0,1,0]
Output: 1

Binary Search,
If arr[mid]>arr[mid-1] and arr[mid]>arr[mid+1], it’s mean mid is arrive peak. More over, maybe is increase or decrease. Then we need to define what is increase and decrease. If arr[mid]>arr[mid-1], it’s mean arr is increasing, I will move left border to mid. Else, it’s mean arr is decreasing. I will move right border to mid+1.

如果用二分查找的方式,當mid>mid-1並且mid>mid+1,則表示已經到了峰值,除此之外,都可能是正在上爬或是下滑。
接著再分成,當mid大於mid-1的值,則表示還在往上爬,那就可以把左邊界移到mid的位置,否則就表示mid小於mid-1的值,則表示在往下走,那就可以把右邊界移到mid+1的位置。

--

--