1095. 山脉数组中查找目标值

在这里插入图片描述
在这里插入图片描述

二分查找

  • 使用二分查找查找山脉数组的峰值位置
  • 将数组以峰值位置为分界线分为左右两部分,并分别使用二分查找查询目标值

二分查找就是每次查找将范围缩小一半

/**
 * // This is MountainArray's API interface.
 * // You should not implement it, or speculate about its implementation
 * interface MountainArray {
 *     public int get(int index) {}
 *     public int length() {}
 * }
 */
 
class Solution {
    public int findInMountainArray(int target, MountainArray mountainArr) {
        int n = mountainArr.length();
        int left = 0, right = n-1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
                left = mid + 1;
            } else {
                right = mid;
            }
        } 
        int peek = left;
        int index = binarySearch(target, mountainArr, 0, peek, true);
        if (index != -1) {
            return index;
        }
        return binarySearch(target, mountainArr, peek + 1, n - 1, false);
    }

    // flag true:递增 false: 递减
    private int binarySearch(int target, MountainArray mountainArr, int left, int right, boolean flag) {
        if (!flag) {
            target *= -1;
        }
        while (left <= right) {
            int mid = (left + right) / 2;
            int cur = mountainArr.get(mid) * (flag ? 1 : -1);
            if (cur > target) {
                right = mid - 1;
            } else if (cur < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
posted @ 2020-10-10 12:28  消灭猕猴桃  阅读(96)  评论(0编辑  收藏  举报