山峰数组的顶部

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/B1IidL

题目描述:

符合下列属性的数组 arr 称为 山峰数组(山脉数组) :
arr.length >= 3
存在 i(0 < i < arr.length - 1)使得:
arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]
给定由整数组成的山峰数组 arr ,返回任何满足 arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 的下标 i ,即山峰顶部。

示例 1:

输入:arr = [0,1,0]
输出:1

示例 2:

输入:arr = [1,3,5,4,2]
输出:2

示例 3:

输入:arr = [0,10,5,2]
输出:1

示例 4:

输入:arr = [3,4,5,1]
输出:2

示例 5:

输入:arr = [24,69,100,99,79,78,67,36,26,19]
输出:2

思路一:

遍历:

  • 初始化i = 1( 1 <= i < arr.length - 1)
  • 遍历判断arr[i - 1] < arr[i] > arr[i + 1]
  • 如果满足,则返回i.
代码实现:
class Solution {
    public int result = 0;
    public int peakIndexInMountainArray(int[] arr) {
        int len = arr.length;
        for (int i = 1; i < len - 1; i++) {
            if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) return i;
        }
        return result;
    }
}
思路二:

二分查找:

  • 初始化mid,判断arr[mid - 1] < arr[mid] > arr[mid+1],如果满足,则返回mid
  • 判断arr[i - 1] < arr[i]
    • true,说明结果在i右边,更新左边界为mid + 1
    • false,说明结果在i左边, 更新右边边为mid
代码实现:
class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int left = 1, right = arr.length - 1;
        int mid = 0;
        while (left < right) {
            mid = (left + right) / 2;
            if (arr[mid - 1] < arr[mid] && arr[mid] > arr[mid + 1]) return mid;
            if (arr[mid - 1] < arr[mid]) {
                left = mid + 1;
            } else {
                right = mid;
            }
            
        }
        return mid;
    }
}

你可能感兴趣的:(山峰数组的顶部)