-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0702-SearchInASortedArrayOfUnknownSize.cs
56 lines (50 loc) · 1.5 KB
/
0702-SearchInASortedArrayOfUnknownSize.cs
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
51
52
53
54
55
56
//-----------------------------------------------------------------------------
// Runtime: 160ms
// Memory Usage: 35.3 MB
// Link: https://leetcode.com/submissions/detail/363451622/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* class ArrayReader {
* public int Get(int index) {}
* }
*/
public class _0702_SearchInASortedArrayOfUnknownSize
{
public int Search(ArrayReader reader, int target)
{
int left = 0, right = 1;
while (reader.Get(right) < target)
{
left = right;
right <<= 1;
}
while (left <= right)
{
var mid = left + (right - left) / 2;
var value = reader.Get(mid);
if (value == target) return mid;
else if (value > target) right = mid - 1;
else
left = mid + 1;
}
return -1;
}
public class ArrayReader
{
private readonly int[] arr;
public ArrayReader(int[] arr)
{
this.arr = arr;
}
public int Get(int index)
{
if (index >= arr.Length) return int.MaxValue;
return arr[index];
}
}
}
}