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
相关推荐
饼饼学习空间智能22 分钟前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
Aphelios38029 分钟前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽
不可求~1 小时前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
Lam Tang1 小时前
APS 系列文章10
java·代理模式
考虑考虑1 小时前
Excel导入时产生特殊字符处理
java·后端·java ee
蛋先生DX2 小时前
你瘦不下来但大模型可以:量化原理了解一下
深度学习·算法·llm
Scabbards_2 小时前
面试Leetcode - Heap 堆
java·leetcode·面试
程序员清风2 小时前
专业再升级!程序员专属显示器明基RD280UG上手实测!
java·后端·面试
(╹◡╹)3 小时前
18.剪枝
算法·机器学习·剪枝
Lam Tang4 小时前
APS 系列文章 08
java·代理模式