[LeetCode] Search in a Sorted Array of Unknown Size 在未知大小的有序數組中搜索

 

Given an integer array sorted in ascending order, write a function to search target in nums.  If target exists, then return its index, otherwise return -1. However, the array size is unknown to you. You may only access the array using an ArrayReader interface, where ArrayReader.get(k) returns the element of the array at index k (0-indexed).html

You may assume all integers in the array are less than 10000, and if you access the array out of bounds, ArrayReader.get will return 2147483647.數組

 

Example 1:less

Input:  = [-1,0,3,5,9,12],  = 9
Output: 4
Explanation: 9 exists in  and its index is 4
arraytargetnums

Example 2:函數

Input:  = [-1,0,3,5,9,12],  = 2
Output: -1
Explanation: 2 does not exist in  so return -1arraytargetnums

 

Note:post

  1. You may assume that all elements in the array are unique.
  2. The value of each element in the array will be in the range [-9999, 9999].

 

這道題給了咱們一個未知大小的數組,讓咱們在其中搜索數字。給了咱們一個ArrayReader的類,咱們能夠經過get函數來得到數組中的數字,若是越界了的話,會返回整型數最大值。既然是有序數組,又要搜索,那麼二分搜索法確定是不二之選,問題是須要知道數組的首尾兩端的位置,才能進行二分搜索,而這道題恰好就是大小未知的數組。因此博主的第一個想法就是先用二分搜索法來求出數組的大小,而後再用一個二分搜索來查找數字,這種方法是能夠經過OJ的。但其實咱們是不用先來肯定數組的大小的,而是能夠直接進行搜索數字,咱們其實是假設數組就有整型最大值個數字,在多餘的位置上至關於都填上了整型最大值,那麼這也是一個有序的數組,咱們能夠直接用一個二分搜索法進行查找便可,參見代碼以下:url

 

// Forward declaration of ArrayReader class.
class ArrayReader;

class Solution {
public:
    int search(const ArrayReader& reader, int target) {
        int left = 0, right = INT_MAX;
        while (left < right) {
            int mid = left + (right - left) / 2, x = reader.get(mid);
            if (x == target) return mid;
            else if (x < target) left = mid + 1;
            else right = mid;
        }
        return -1;
    }
};

 

相似題目:spa

Binary Searchcode

 

相似題目:htm

https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/blog

https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/discuss/171669/Straight-forward-binary-search.

https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/discuss/151685/Shortest-and-cleanest-Java-solution-so-far...

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索