This is an interactive problem.
You have a sorted array of unique elements and an unknown size. You do not have an access to the array but you can use the ArrayReader
interface to access it. You can call ArrayReader.get(i)
that:
- returns the value at the
ith
index (0-indexed) of the secret array (i.e.,secret[i]
), or - returns
231 - 1
if thei
is out of the boundary of the array.
You are also given an integer target
.
Return the index k
of the hidden array where secret[k] == target
or return -1
otherwise.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: secret = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in secret and its index is 4.
Example 2:
Input: secret = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in secret so return -1.
Constraints:
1 <= secret.length <= 104
-104 <= secret[i], target <= 104
secret
is sorted in a strictly increasing order.
在未知大小的有序數組中搜索。
題干即是題意,給一個有序數組但是不告知數組長度,請找一個 target 數字。
思路是用二分法。先設一個變量 high,因為不確定 input 數組的長度所以只能每次乘以二去試探 high 位置上的數字和 target 數字的大小關系。
時間O(logn)
空間O(1)
JS實現
1 /** 2 * @param {ArrayReader} reader 3 * @param {number} target 4 * @return {number} 5 */ 6 var search = function (reader, target) { 7 let hi = 1; 8 while (reader.get(hi) < target) { 9 hi = hi << 1; 10 } 11 let low = hi >> 1; 12 while (low <= hi) { 13 let mid = Math.floor(low + (hi - low) / 2); 14 if (reader.get(mid) > target) { 15 hi = mid - 1; 16 } else if (reader.get(mid) < target) { 17 low = mid + 1; 18 } else { 19 return mid; 20 } 21 } 22 return -1; 23 };
Java實現
1 class Solution { 2 public int search(ArrayReader reader, int target) { 3 int hi = 1; 4 while (reader.get(hi) < target) { 5 hi = hi << 1; 6 } 7 int low = hi >> 1; 8 while (low <= hi) { 9 int mid = low + (hi - low) / 2; 10 if (reader.get(mid) > target) { 11 hi = mid - 1; 12 } else if (reader.get(mid) < target) { 13 low = mid + 1; 14 } else { 15 return mid; 16 } 17 } 18 return -1; 19 } 20 }