-
Notifications
You must be signed in to change notification settings - Fork 2
/
1095.find-in-mountain-array.java
66 lines (61 loc) · 1.7 KB
/
1095.find-in-mountain-array.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode id=1095 lang=java
*
* [1095] Find in Mountain Array
*/
// @lc code=start
/**
* // 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 size = mountainArr.length();
int mid = 0;
int peak = 0;
//find the index of the mountain number
int low = 0;
int high = size - 1;
while (low < high) {
mid = low + (high - low) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1;
peak = mid + 1;
} else {
high = mid;
}
}
//find the target in the left subarray
low = 0;
high = peak;
while (low <= high) {
mid = low + (high - low) / 2;
if (mountainArr.get(mid) == target) {
return mid;
} else if (mountainArr.get(mid) < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
//find the target in the right subarray
low = peak;
high = size - 1;
while (low <= high) {
mid = low + (high - low) / 2;
if (mountainArr.get(mid) == target) {
return mid;
} else if (mountainArr.get(mid) < target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
}
// @lc code=end