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

Appearance settings

Latest commit

 

History

History
History
50 lines (48 loc) · 1.43 KB

File metadata and controls

50 lines (48 loc) · 1.43 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import java.util.Arrays;
public class SearchMountainArray {
public static void main(String[] args) {
int[] nums = {1,2,3,4,5,4,3,2,1};
int target = 2;
int peak = mountainArray(nums);
int asc = binarySearch(nums,target,0,peak);
int dsc = binarySearch(nums,target,peak,nums.length-1);
int[] nums1 = {asc,dsc};
System.out.println(Arrays.toString(nums1));
}
public static int mountainArray(int[] nums){
int start = 0;
int end = nums.length-1;
while(start < end) {
int mid = (start + end) / 2;
if (nums[mid] > nums[mid + 1]) {
end = mid;
} else if(nums[mid] <= nums[mid + 1]) {
start = mid + 1;
}
}
return start;
}
public static int binarySearch(int[] nums, int target,int start,int end){
boolean isAsc = nums[start] < nums[end];
while(start<=end){
int mid = (start+end)/2;
if(nums[mid]==target) {
return mid;
}
if(isAsc) {
if(target>nums[mid]){
start = mid+1;
}else{
end = mid-1;
}
}else {
if(target<nums[mid]){
start = mid+1;
}else{
end = mid-1;
}
}
}
return -1;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.