剑指 Offer II 069. 山峰数组的顶部

1. Question

符合下列属性的数组 arr 称为 山峰数组(山脉数组) :

  • arr.length >= 3
  • 存在i0 < 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 ,即山峰顶部。

2. Examples

示例 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

3. Constraints

  • 3 <= arr.length <= 104
  • 0 <= arr[i] <= 106
  • 题目数据保证 arr 是一个山脉数组

进阶:很容易想到时间复杂度 O(n) 的解决方案,你可以设计一个 O(log(n)) 的解决方案吗?

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/B1IidL 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class Solution {
  public int peakIndexInMountainArray(int[] arr) {
    int max = Arrays.stream(arr).max().getAsInt();
    for (int i = 0; i < arr.length; i++) {
      if (arr[i] == max) {
        return i;
      }
    }
    return -1;
  }
}

二分

class Solution {
  public int peakIndexInMountainArray(int[] arr) {
    // 这里有个边界问题,容易超出索引
    int left = 1;
    int right = arr.length - 2;
    int ans = -1;

    while (left <= right) {
      int mid = (left + right) / 2;
      if (arr[mid - 1] <= arr[mid]) {
        ans = mid;
        left = mid + 1;
      } else {
        ans = mid - 1;
        right = mid - 1;
      }
    }
    return ans;
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""