[LeetCode] Find in Mountain Array

1095. Find in Mountain Array

(This problem is an interactive problem.)

You may recall that an array arr is a mountain array if and only if:

  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < … < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > … > arr[arr.length - 1]

Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.

You cannot access the mountain array directly. You may only access the array using a MountainArray interface:

  • MountainArray.get(k) returns the element of the array at index k (0-indexed).
  • MountainArray.length() returns the length of the array.

Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* // This is the MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* class MountainArray {
* public:
* int get(int index);
* int length();
* };
*/

class Solution {
int top(MountainArray &A, int l, int r) {
while(l < r) {
int m = (l + r) / 2;
if(A.get(m) > A.get(m + 1)) {
r = m;
} else {
l = m + 1;
}
}
return l;
}
int binarySearch(MountainArray &A, int l, int r, int t) {
while(l <= r) {
int m = (l + r) / 2, mv = A.get(m);
if(mv == t) return m;
else if(mv < t) l = m + 1;
else r = m - 1;
}
return - 1;
}
int reverseBinarySearch(MountainArray &A, int l, int r, int t) {
while(l <= r) {
int m = (l + r) / 2, mv = A.get(m);
if(mv == t) return m;
else if(mv < t) r = m - 1;
else l = m + 1;
}
return -1;
}
public:
int findInMountainArray(int t, MountainArray &A) {
int n = A.length();
int l = 0, r = n-1, m = top(A,l,r);
int bS = binarySearch(A,l,m,t);
if(bS == -1) return reverseBinarySearch(A,m+1,r,t);
return bS;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/find-in-mountain-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.