public class FindMountainArray_1095 {
public static void main(String[] args) {
int[] array = { 0, 1, 2, 4, 2, 1 };
int target = 3;
MountainArray mountainArray = new MountainArrayImpl(array);
System.out.println(findInMountainArray(target, mountainArray));
}
public static int findInMountainArray(int target, MountainArray mountainArray) {
int len = mountainArray.length();
int top = findMountainTop(mountainArray, 0, len - 1);
int res = findAscArray(mountainArray, 0, top, target);
if (res != -1) {
return res;
}
return findDecArray(mountainArray, top + 1, len - 1, target);
}
public static int findMountainTop(MountainArray mountainArr, int left, int right) {
while (left < right) {
int mid = left + (right - left) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
public static int findAscArray(MountainArray mountainArr, int left, int right, int target) {
while (left < right) {
int mid = left + (right - left) / 2;
if (mountainArr.get(mid) < target) {
left = mid + 1;
} else {
right = mid;
}
}
if (mountainArr.get(left) == target) {
return left;
}
return -1;
}
public static int findDecArray(MountainArray mountainArr, int left, int right, int target) {
while (left < right) {
int mid = left + (right - left) / 2;
if (mountainArr.get(mid) > target) {
left = mid + 1;
} else {
right = mid;
}
}
if (mountainArr.get(left) == target) {
return left;
}
return -1;
}
}
class MountainArrayImpl implements MountainArray {
private int[] array;
private int length;
public MountainArrayImpl(int[] array) {
this.array = array;
this.length = array.length;
}
@Override
public int get(int index) {
return this.array[index];
}
@Override
public int length() {
return this.length;
}
}
interface MountainArray {
public int get(int index);
public int length();
}