Код: Выделить всё
public class InfiniteElement{
public static void main(String[] args) {
int[] arr = {1, 2, 4, 6, 8, 9, 10 , 13, 16, 19, 20 ,23, 27, 40, 42, 44};
int target = 44;
System.out.print(findPos(arr, target));
}
static int findPos(int[] arr, int target){
int start = 0;
int end = 1;
while(target > arr[end]){
//temp will the new start
int temp = end + 1;
//instead of breaking the box we are multiplying
//so that the chunk of boxes increase the window
//it will help us to find the target in particular boxes
// end = end + (end - start + 1) * 2;
// + 1 is because we are using the indices
end = end + (end - start + 1) * 2;
start = temp;
}
return binarySearch(arr, target, start, end);
}
static int binarySearch(int[] arr, int target, int start, int end){
while(start target){
end = mid - 1;
} else{
start = mid + 1;
}
}
return -1;
}
}
Привет, ребята, как дела. Это из видео Кунала Кушвахи «Решение задач двоичного поиска». 1:28:03 Вопрос 5: Положение элемента в бесконечном отсортированном массиве.
Когда массив arr = {1, 2, 4, 6, 8, 9, 10, 13, 16, 19, 20, 23, 27, 40, 42, 44}, target = 44;
Получаю ошибку типа: Индекс массива вышел за пределы. Если кто-нибудь найдет решение, дайте мне знать.
Подробнее здесь: https://stackoverflow.com/questions/787 ... rray-by-ku