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
相关推荐
编程、小哥哥35 分钟前
Java面试实战:从Spring Boot到分布式缓存的深度探索
java·spring boot·redis·微服务·grpc·缓存技术·面试技巧
在未来等你36 分钟前
互联网大厂Java求职面试:Spring AI与大模型交互的高级模式与自定义开发
java·微服务·云原生·大模型·spring ai
智驱力人工智能39 分钟前
AI移动监测:仓储环境安全的“全天候守护者”
人工智能·算法·安全·边缘计算·行为识别·移动监测·动物检测
androidwork43 分钟前
Android Kotlin权限管理最佳实践
android·java·kotlin
sakoba1 小时前
Tomcat简述介绍
java·tomcat
键盘客2 小时前
Spring Boot 配置明文密码加密,防泄漏
java·spring boot·后端·spring
代码小将2 小时前
力扣992做题笔记
算法·leetcode
编程绿豆侠2 小时前
力扣HOT100之二叉树:199. 二叉树的右视图
算法·leetcode·职场和发展
二进制小甜豆2 小时前
SpringBoot快速上手
java·spring boot·maven
苹果酱05673 小时前
Golang中的runtime.LockOSThread 和 runtime.UnlockOSThread
java·vue.js·spring boot·mysql·课程设计