leetcode - 852. Peak Index in a Mountain Array

Description

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 a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

You must solve it in O(log(arr.length)) time complexity.

Example 1:

复制代码
Input: arr = [0,1,0]
Output: 1

Example 2:

复制代码
Input: arr = [0,2,1,0]
Output: 1

Example 3:

复制代码
Input: arr = [0,10,5,2]
Output: 1

Constraints:

复制代码
3 <= arr.length <= 10^5
0 <= arr[i] <= 10^6
arr is guaranteed to be a mountain array.

Solution

Use binary search to solve this problem. For any middle index, it either locates at the left of the peak, or the right of the peak. If at the left, then discard the left half, otherwise discard the right half.

Time complexity: o ( log ⁡ n ) o(\log n) o(logn)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        left, right = 0, len(arr) - 1
        while left < right:
            mid = (left + right) >> 1
            if arr[mid - 1] < arr[mid] < arr[mid + 1]:
                left = mid + 1
            elif arr[mid - 1] > arr[mid] > arr[mid + 1]:
                right = mid
            else:
                return mid
相关推荐
RainbowSea10 分钟前
伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 06
java·spring boot·后端
金融小师妹18 分钟前
AI多因子模型解析:黄金涨势受阻与美联储9月降息政策预期重构
大数据·人工智能·算法
CHENFU_JAVA40 分钟前
EasyExcel 合并单元格最佳实践:基于注解的自动合并与样式控制
java·excel
NAGNIP1 小时前
LLaMA 3:离 AGI 更近一步?
算法
PineappleCoder1 小时前
力扣【2348. 全0子数组的数目】——从暴力到最优的思考过程
前端·javascript·算法
华仔啊1 小时前
3行注解干掉30行日志代码!Spring AOP实战全程复盘
java·spring boot·后端
Fireworkitte2 小时前
Tomcat 的核心脚本catalina.sh 和 startup.sh的关系
java·tomcat
风吹落叶32572 小时前
深入解析JVM内存管理与垃圾回收机制
java·开发语言·jvm
叶~璃2 小时前
人工智能驱动的开发变革
java
_poplar_2 小时前
08.5【C++ 初阶】实现一个相对完整的日期类--附带源码
c语言·开发语言·数据结构·c++·vscode·算法·vim