Search in a Big Sorted Array

Given a big sorted array with positive integers sorted by ascending order. The array is so big so that you can not get the length of the whole array directly, and you can only access the kth number by ArrayReader.get(k) (or ArrayReader->get(k) for C++). Find the first index of a target number. Your algorithm should be in O(log k), where k is the first index of the target number.

Return -1, if the number doesn't exist in the array.

Example Given [1, 3, 6, 9, 21, ...], and target = 3, return 1.

Given [1, 3, 6, 9, 21, ...], and target = 4, return -1.

Notes:

  1. Double size the index to find the end
  2. Binary search
    public int searchBigSortedArray(ArrayReader reader, int target) {
        int k = 1;
        int v = reader.get(k-1);

        // if (target < v) {
        //     return -1;
        // }

        while(v < target) {
            k *= 2;
            v = reader.get(k-1);
        }

        int start = (k-1)/2;
        int end = k-1;

        while(start+1 < end) {
            int middle = start + (end-start)/2;
            int middleValue = reader.get(middle);

            if (middleValue < target) {
                start = middle;
            } else {
                end = middle;
            }
        }

        if (reader.get(start) == target) {
            return start;
        }

        if (reader.get(end) == target) {
            return end;
        }

        return -1;
    }

results matching ""

    No results matching ""