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
相关推荐
爱编程的小白L1 小时前
基于springboot志愿服务管理系统设计与实现(附源码)
java·spring boot·后端
WHS-_-20221 小时前
A Density Clustering-Based CFAR Algorithm for Ship Detection in SAR Images
算法·5g
聪明的笨猪猪3 小时前
Java Redis “持久化”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
聪明的笨猪猪3 小时前
Java Redis “核心基础”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
Miraitowa_cheems3 小时前
LeetCode算法日记 - Day 68: 猜数字大小II、矩阵中的最长递增路径
数据结构·算法·leetcode·职场和发展·贪心算法·矩阵·深度优先
奋斗的小monkey5 小时前
Spring Boot 3.x核心特性与性能优化实战
java·spring boot·微服务·性能优化·响应式编程
灵感__idea5 小时前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
程序猿DD6 小时前
将 GPU 级性能带到企业级 Java:CUDA 集成实用指南
java·架构
学习2年半6 小时前
小米笔试题:一元一次方程求解
算法