0
0

More than 1 year has passed since last update.

Leetcode 852. Peak Index in a Mountain Array

Last updated at Posted at 2023-07-25

アプローチ1

Brute-force

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

アプローチ2

二分探索

class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int left = 0;
        int right = arr.length - 1;

        while (left < right) {
            int mid = (left + right) / 2;

            if (arr[mid] < arr[mid + 1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0