05 August 2008
Given an integer array sorted in ascending order, write a function to search
in 1
target
. If 1
nums
exists, then return its index, otherwise return 1
target
. However, the array size is unknown to you. You may only access the array using an 1
-1
interface, where 1
ArrayReader
returns the element of the array at index 1
ArrayReader.get(k)
(0-indexed).1
k
You may assume all integers in the array are less than
, and if you access the array out of bounds, 1
10000
will return 1
ArrayReader.get
.1
2147483647
Example 1:
1
2
3
Input: array = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
1
2
3
Input: array = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1
[-9999, 9999]
.1
[1, 10^4]
.倍增找到右边界,然后二分。
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
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* public int get(int index) {}
* }
*/
class Solution {
public int search(ArrayReader reader, int target) {
long left = 0, right = 1;
while (reader.get((int)right) < target) {
right *= 2;
}
while (left + 1 < right) {
long mid = left + (right - left) / 2;
if (reader.get((int)mid) == target) {
return (int)mid;
} else if (reader.get((int)mid) < target) {
left = mid;
} else {
right = mid;
}
}
if (reader.get((int)left) == target) return (int)left;
return reader.get((int)right) == target ? (int)right : -1;
}
}