[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).

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:

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

Example 2:

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

 

Note:

  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的。但其實我們是不用先來確定數組的大小的,而是可以直接進行搜索數字,我們實際上是假設數組就有整型最大值個數字,在多余的位置上相當於都填上了整型最大值,那么這也是一個有序的數組,我們可以直接用一個二分搜索法進行查找即可,參見代碼如下:

 

// 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;
    }
};

 

類似題目:

Binary Search

 

類似題目:

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

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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM