File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * // This is MountainArray's API interface.
3
+ * // You should not implement it, or speculate about its implementation
4
+ * interface MountainArray {
5
+ * public int get(int index) {}
6
+ * public int length() {}
7
+ * }
8
+ */
9
+
10
+ class Solution {
11
+ public int findInMountainArray (int target , MountainArray mountainArr ) {
12
+ int n = mountainArr .length ();
13
+ int start = 1 ;
14
+ int end = n - 2 ;
15
+ while (start != end ) {
16
+ int mid = (start + end ) / 2 ;
17
+ if (mountainArr .get (mid ) < mountainArr .get (mid + 1 )) {
18
+ start = mid + 1 ;
19
+ } else {
20
+ end = mid ;
21
+ }
22
+ }
23
+ int peakIndex = start ;
24
+ start = 0 ;
25
+ end = peakIndex ;
26
+ while (start != end ) {
27
+ int mid = (start + end ) / 2 ;
28
+ if (mountainArr .get (mid ) < target ) {
29
+ start = mid + 1 ;
30
+ } else {
31
+ end = mid ;
32
+ }
33
+ }
34
+ if (mountainArr .get (start ) == target ) {
35
+ return start ;
36
+ }
37
+ start = peakIndex + 1 ;
38
+ end = n - 1 ;
39
+ while (start != end ) {
40
+ int mid = (start + end ) / 2 ;
41
+ if (mountainArr .get (mid ) > target ) {
42
+ start = mid + 1 ;
43
+ } else {
44
+ end = mid ;
45
+ }
46
+ }
47
+ return mountainArr .get (start ) == target ? start : -1 ;
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments