Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit95795bb

Browse files
committed
Create: 1095-find-in-mountain-array.java
1 parent735d3c7 commit95795bb

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

‎java/1095-find-in-mountain-array.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+
classSolution {
11+
publicintfindInMountainArray(inttarget,MountainArraymountainArr) {
12+
intmaxIndex =findMax(mountainArr);
13+
intleftResult =binarySearchLeft(mountainArr,target,maxIndex);
14+
intrightResult =binarySearchRight(mountainArr,target,maxIndex);
15+
16+
return (leftResult == -1 &&rightResult == -1) ? -1 :leftResult == -1 ?rightResult :leftResult;
17+
}
18+
19+
publicintfindMax(MountainArrayarray) {
20+
intleft =0;
21+
intright =array.length() -1;
22+
23+
while (left<=right) {
24+
intmid =left + (right -left)/2;
25+
if (array.get(mid) <array.get(mid +1)) {
26+
left =mid +1;
27+
}else {
28+
right =mid -1;
29+
}
30+
}
31+
32+
returnleft;
33+
}
34+
35+
publicintbinarySearchLeft(MountainArrayarray,inttarget,intright) {
36+
intleft =0;
37+
38+
while (left<=right) {
39+
intmid =left + (right -left)/2;
40+
intmidValue =array.get(mid);
41+
if (midValue <target) {
42+
left =mid +1;
43+
}elseif (midValue >target) {
44+
right =mid -1;
45+
}else {
46+
returnmid;
47+
}
48+
}
49+
return -1;
50+
}
51+
52+
publicintbinarySearchRight(MountainArrayarray,inttarget,intleft) {
53+
intright =array.length() -1;
54+
55+
while (left <=right) {
56+
intmid =left + (right -left)/2;
57+
intmidValue =array.get(mid);
58+
59+
if (midValue <target) {
60+
right =mid -1;
61+
}elseif (midValue >target) {
62+
left =mid +1;
63+
}else {
64+
returnmid;
65+
}
66+
}
67+
return -1;
68+
}
69+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp