-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 6 ms (44.79%), Space: 7.2 MB (43.62%) - LeetHub
- Loading branch information
1 parent
951b5af
commit a054684
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
64 changes: 64 additions & 0 deletions
64
1095-find-in-mountain-array/1095-find-in-mountain-array.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/** | ||
* // 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 { | ||
public: | ||
int findInMountainArray(int target, MountainArray &mountainArr) { | ||
int n=mountainArr.length(); | ||
int i=0; | ||
int j=n-1; | ||
int peak=-1; | ||
while(i<=j) | ||
{ | ||
int mid=(i+j)/2; | ||
int t=mountainArr.get(mid); | ||
if(t>mountainArr.get(mid-1) && t>mountainArr.get(mid+1)) | ||
{ | ||
peak=mid; | ||
break; | ||
} | ||
else if(t<mountainArr.get(mid+1) && t>mountainArr.get(mid-1)) | ||
{ | ||
i=mid; | ||
} | ||
else | ||
{ | ||
j=mid; | ||
} | ||
} | ||
|
||
//in first half | ||
i=0; | ||
j=peak; | ||
while(i<=j) | ||
{ | ||
int mid=(i+j)/2; | ||
int t=mountainArr.get(mid); | ||
if(t==target)return mid; | ||
else if(t<target) | ||
i=mid+1; | ||
else | ||
j=mid-1; | ||
} | ||
i=n-1; | ||
j=peak; | ||
while(j<=i) | ||
{ | ||
int mid=(i+j)/2; | ||
int t=mountainArr.get(mid); | ||
if(t==target)return mid; | ||
else if(t<target) | ||
i=mid-1; | ||
else | ||
j=mid+1; | ||
} | ||
return -1; | ||
} | ||
}; |