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
相关推荐
kimble_xia@oracle7 分钟前
SQL 笔记
java·数据库·oracle
David爱编程22 分钟前
深度解析:synchronized 性能演进史,从 JDK1.6 到 JDK17
java·后端
Tim_1023 分钟前
【算法专题训练】20、LRU 缓存
c++·算法·缓存
脑子慢且灵41 分钟前
【JavaWeb】一个简单的Web浏览服务程序
java·前端·后端·servlet·tomcat·web·javaee
Lris-KK1 小时前
【Leetcode】高频SQL基础题--1341.电影评分
sql·leetcode
B612 little star king1 小时前
力扣29. 两数相除题解
java·算法·leetcode
野犬寒鸦1 小时前
力扣hot100:环形链表(快慢指针法)(141)
java·数据结构·算法·leetcode·面试·职场和发展
时光追逐者1 小时前
C# 哈希查找算法实操
算法·c#·哈希算法
上官浩仁1 小时前
springboot synchronized 本地锁入门与实战
java·spring boot·spring
Gogo8161 小时前
java与node.js对比
java·node.js