[CareerCup] 11.5 Search Array with Empty Strings 搜尋含有空字串的陣列

Grandyang發表於2015-10-17

 

11.5 Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string.
 EXAMPLE
 Input: find "ball" in {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}
 Output: 4

 

這道題給了我們一個有序的字串陣列,但是在中間加入了很多空字串,讓我們來查詢一個給定字串。如果沒有這些空字串,那麼我們用二分查詢法很容易搜尋,但是這些空字串就有很大的干擾作用。那麼我們要在原有的二分查詢法上做修改,類似的修改二分查詢法的裡有Search in Rotated Sorted Array 在旋轉有序陣列中搜尋Search in Rotated Sorted Array II 在旋轉有序陣列中搜尋之二。這道題我們的思路是,查詢中間的字串,如果是空字串,那麼我們用二分查詢法來找周圍最近的非空字串,然後把mid移到飛空字串的位置,繼續二分查詢。相當於二分查詢中又巢狀了一個二分查詢,參見程式碼如下:

 

class Solution {
public:
    int search(vector<string> strings, string str) {
        int first = 0, last = strings.size() - 1;
        while (first <= last) {
            int mid = first + (last - first) / 2;
            if (strings[mid].empty()) {
                int left = mid - 1, right = mid + 1;
                while (true) {
                    if (left < first && right > last) return -1;
                    else if (right <= last && !strings[right].empty()) {
                        mid = right; break;
                    }
                    else if (left >= first && !strings[left].empty()) {
                        mid = left; break;
                    }
                    ++right;
                    --left;
                }
            }
            int res = strings[mid].compare(str);
            if (res == 0) return mid;
            else if (res < 0) first = mid + 1;
            else last = mid - 1;
        }    
        return -1;
    }
};

 

相關文章