其他分享
首页 > 其他分享> > 1095. 山脉数组中查找目标值

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

作者:互联网

(这是一个 交互式问题 )

给你一个 山脉数组 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() - 会返回该数组的长度

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

class Solution {

    private MountainArray mountainArray;

    private boolean isHigher(int x, int y) {
        int n = mountainArray.length();
        if (y == -1 || y == n) {
            return true;
        }
        return mountainArray.get(x) > mountainArray.get(y);
    }

    private int findHighest() {
        int left = 0, right = mountainArray.length() - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (isHigher(mid, mid + 1) && isHigher(mid, mid - 1)) {
                return mid;
            }
            if (isHigher(mid + 1, mid)) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    private int search(int left, int right, int target, boolean asc) {
        while (left <= right) {
            int mid = (left + right) >> 1;
            int midVal = mountainArray.get(mid);
            if (midVal == target) {
                return mid;
            }
            if (midVal < target) {
                if (asc) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            } else {
                if (asc) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
        }
        return -1;
    }

    public int findInMountainArray(int target, MountainArray mountainArr) {
        this.mountainArray = mountainArr;

        int highestIndex = findHighest();

        int idx = search(0, highestIndex, target, true);
        if (idx != -1) {
            return idx;
        }
        idx = search(highestIndex, mountainArray.length() - 1, target, false);
        return idx;
    }
}

interface MountainArray {
    default int get(int index) {
        return 0;
    }

    default int length() {
        return 0;
    }
}

标签:1095,return,target,int,mid,mountainArray,length,查找,目标值
来源: https://www.cnblogs.com/tianyiya/p/15719025.html