Java를 사용하여 무한 배열에서 요소 찾기
Problem Statement
Given an infinite array of sorted integers, we need to find the index of a given target number. The array is "infinite," meaning we cannot determine its size in advance, so we can't just apply a traditional binary search directly.
Approach Overview
Start with a small range: Initially, assume that the element lies within a small range (say, between indices 0 and 1).
Dynamically increase the range: If the target element is not found in the initial range, we double the size of the range to search further. This exponential growth allows us to quickly hone in on the range where the target might be located.
Binary search within the range: Once we determine a suitable range that contains the target, we apply binary search to efficiently find the target's index.
The Code
public class InfiniteArraySearch { public static void main(String[] args) { // Define the array (for demonstration purposes, treat this as infinite) int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; int target = 6; // Call the function to find the target element int result = findElementInInfiniteArray(arr, target); System.out.println("Element found at index: " + result); } // Function to find the target in the infinite array static int findElementInInfiniteArray(int[] arr, int target) { // Start with a small range int start = 0; int end = 1; // Dynamically increase the range until the target is within bounds while (target > arr[end]) { int newStart = end + 1; // Update start to one after the current end end = end + (end - start + 1) * 2; // Double the range start = newStart; // Move the start to newStart } // Perform binary search within the determined range return binarySearch(arr, target, start, end); } // Standard binary search implementation static int binarySearch(int[] arr, int target, int start, int end) { while (start <= end) { int mid = start + (end - start) / 2; if (target < arr[mid]) { end = mid - 1; // Move the end to the left } else if (target > arr[mid]) { start = mid + 1; // Move the start to the right } else { return mid; // Element found } } return -1; // Element not found } }
Explanation of the Code
1. Main Function
The main function defines an example array arr and a target value 6. For simplicity, we assume the array is finite here, but conceptually, we treat it as infinite. The main function then calls findElementInInfiniteArray to search for the target, and prints the index if found.
2. Range Expansion (Linearly Expanding the Search Area)
In the findElementInInfiniteArray method:
- We begin by assuming that the element lies within the range [0, 1].
- If the target is greater than the value at arr[end], it means the target is not within the current range. So, we expand the range exponentially by doubling it (end = end + (end - start + 1) * 2). This effectively allows us to cover more ground in each iteration.
3. Binary Search
Once we know that the target must lie between start and end, we perform a standard binary search. Binary search is an efficient way to search in sorted arrays, as it reduces the search space by half at each step. The key comparisons are:
- If the target is less than the middle element (arr[mid]), search the left half.
- If the target is greater, search the right half.
- If the target matches the middle element, return its index.
4. Edge Cases
- If the target is smaller than the smallest element in the array, or if the array doesn't contain the target at all, the algorithm will return -1.
Time Complexity
Range Expansion: The range doubles with each iteration, so it takes O(log N) operations to find the right range where the target lies.
Binary Search: Once the range is found, binary search runs in O(log M), where M is the size of the range.
Thus, the overall time complexity is approximately O(log N + log M).
위 내용은 Java를 사용하여 무한 배열에서 요소 찾기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

많은 응용 프로그램 시나리오에서 정렬을 구현하기 위해 이름으로 이름을 변환하는 솔루션, 사용자는 그룹으로, 특히 하나로 분류해야 할 수도 있습니다.

시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

전자 상거래 플랫폼에서 SKU 및 SPU 테이블의 디자인에 대한 자세한 설명이 기사는 전자 상거래 플랫폼에서 SKU 및 SPU의 데이터베이스 설계 문제, 특히 사용자 정의 판매를 처리하는 방법에 대해 논의 할 것입니다 ...

Redis 캐싱 솔루션은 제품 순위 목록의 요구 사항을 어떻게 인식합니까? 개발 과정에서 우리는 종종 a ... 표시와 같은 순위의 요구 사항을 처리해야합니다.
