leetcode第1095 山脉数组中查找数组值

1095、山脉数组中查找数组值

来自leetcode1095题

(这是一个 交互式问题 )
给你一个 山脉数组 mountainArr,请你返回能够使得 mountainArr.get(index) 等于 target 最小 的下标 index 值。
如果不存在这样的下标 index,就请返回 -1。

何为山脉数组?如果数组 A 是一个山脉数组的话,那它满足如下条件:
首先,A.length >= 3
其次,在 0 < i < A.length - 1 条件下,存在 i 使得:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]

你将 不能直接访问该山脉数组,必须通过 MountainArray 接口来获取数据:
MountainArray.get(k) - 会返回数组中索引为k 的元素(下标从 0 开始)
MountainArray.length() - 会返回该数组的长度

注意:
对 MountainArray.get 发起超过 100 次调用的提交将被视为错误答案。

示例 1:
输入:array = [1,2,3,4,5,3,1], target = 3
输出:2
解释:3 在数组中出现了两次,下标分别为 2 和 5,我们返回最小的下标 2。
示例 2:
输入:array = [0,1,2,4,2,1], target = 3
输出:-1
解释:3 在数组中没有出现,返回 -1。

提示:
3 <= mountain_arr.length() <= 10000
0 <= target <= 10^9
0 <= mountain_arr.get(index) <= 10^9

题解:

使用二分法,难点二分法的判定函数

/**
 * // 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) {
        //array = [1,2,3,4,5,3,1], target = 3
        int len = mountainArr.length();
        int peakIndex = findTopMontainIndex(0, len - 1, mountainArr);
        if(mountainArr.get(peakIndex) == target) {
            return peakIndex;
        }
        int res = findSortedArray(0, peakIndex - 1, mountainArr, target);
        if(res != -1) {
            return res;
        }
        return findReverseArray(peakIndex + 1, len - 1, mountainArr, target);
    }

    public int findTopMontainIndex(int left, int right, MountainArray mountainArr) {
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(mountainArr.get(mid) < mountainArr.get(mid + 1)) {
                left = mid + 1;
            }else {
                right = mid;
            }
        }
        return left;
    }

    public int findSortedArray(int left, int right, MountainArray mountainArr, int target) {
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(target > mountainArr.get(mid)) {
                left = mid + 1;
            }else {
                right = mid;
            }
        }
        if(mountainArr.get(left) == target) {
            return left;
        }
        return -1;
    }

    public int findReverseArray(int left, int right, MountainArray mountainArr, int target) {
        //逆序数组
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(target < mountainArr.get(mid)) {
                //[mid + 1, right]
                left = mid + 1;
            }else {
                right = mid;
            }
        }
        if(mountainArr.get(left) == target) {
            return left;
        }
        return -1;
    }
    
}
posted @ 2020-05-07 10:57  我见青山应如是  阅读(129)  评论(0编辑  收藏  举报