forked from super30admin/Binary-Search-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchUnknownSizeArray.java
More file actions
33 lines (30 loc) · 884 Bytes
/
Copy pathSearchUnknownSizeArray.java
File metadata and controls
33 lines (30 loc) · 884 Bytes
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
// #702. Search in a Sorted Array of Unknown Size
// Time Complexity : O(log(n)): n is the length of the array
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// interface ArrayReader {
// public int get(int index) {}
// }
public class SearchUnknownSizeArray {
public int search(ArrayReader reader, int target) {
int low = 0;
int high = 1;
while(target > reader.get(high)){
low = high;
high = high*2;
}
while (low<=high){
int mid = low + (high-low)/2;
if(reader.get(mid) == target){
return mid;
} else if( target < reader.get(mid)){
high = mid-1;
}
else{
low = mid+1;
}
}
return -1;
}
}