leetcode - [852] Peak Index in a Mountain Array

2020/07/15

问题描述

Let’s call an array A a mountain if the following properties hold:

A.length >= 3

There exists some 0 < i < A.length - 1 such that
A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1]

Given an array that is definitely a mountain, return any i such that

A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1].

寻找数组中的波峰,并返回其索引。

举个例子:

Input: [0,2,1,0]
Output: 1

类似题:

[162] Find Peak Element

解法1

162题一样。

直接来看下实现:

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        
        int n = A.length;
        int l = 0, r = n - 1;
        while (l < r){
            int mid = l + r + 1 >> 1;
            if (A[mid] > A[mid - 1]) l = mid;
            else r = mid - 1;
        }
        return l;
    }
}

Enjoy it !


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory