二分查找算法及其擴展

二分查找是面試中手寫代碼經常遇到的題目, 昨天還有同事說有個面試, 手寫代碼這一環節就是二分查找.
在下面兩個版本的實現中, 假設傳入的數組是遞增的.

在面試的時候, 需要問清楚, 傳入的數組的特點:

  • 是否是排好序的
  • 遞增還是遞減
  • 當數字有重復時, 是否返回任意一個數的下標即可
  • 同時, 查找時需要特別注意邊界條件

二分查找實現起來不算難, 需要特別注意這些細節. 正是這些細節決定了你是否可以通過面試的這個環節.

Case 1: 二分查找一個數的下標, 當有多個目標數存在時,返回任意一個.

遞歸版本

int BinarySearch::search(const std::vector<int>& datas,
                         const int dest)
{
    LOG(INFO) << "Enter: " << __func__;
    int ret = -1; 
    ret = searchInternal(datas, 0, datas.size() - 1, dest);
    LOG(INFO) << "Leave: " << __func__;
    return ret;
}

int BinarySearch::searchInternal(const std::vector<int>& datas,
                                 const int startIndex,
                                 const int endIndex,
                                 const int dest)
{
    if (startIndex > endIndex)
    {   
        LOG(INFO) << "Not Found Dest: " << dest;
        return -1; 
    }   
    int mid = startIndex + (endIndex - startIndex) / 2;
    if (datas[mid] == dest)
    {   
        return mid;
    }   
    else if (datas[mid] > dest)
    {   
        return searchInternal(datas, startIndex, mid - 1, dest);
    }   
    else
    {   
        return searchInternal(datas, mid + 1, endIndex, dest);
    }   
}

非遞歸版本

只實現了internal方法

int BinarySearch::searchInternal(const std::vector<int>& datas,
                                 int startIndex,
                                 int endIndex,
                                 const int dest)
{
    int ret = -1; 
    while (startIndex <= endIndex)
    {   
        int midIndex = startIndex + (endIndex - startIndex) / 2;
        if (datas[midIndex] == dest)
        {   
            ret = midIndex; 
            break;
        }   
        else if (datas[midIndex] < dest)
        {   
            startIndex = midIndex + 1;
        }   
        else
        {   
            endIndex = midIndex - 1;
        }   
    }   
    return ret;
}

Case 2: 查找第一個大于或等于某個數的下標

算法思想: 等待查找失敗,那么查找失敗的最后一個區間的下一個元素, 即是滿足條件的元素.
例如:
數組: 1 2 3 5 6 7
目標數: 4
查找區間的起始index和結束index的變化見下表

查找輪數 startIndex endIndex
1 0 5
2 0 2
3 1 2
4 2 2
5 3 2

結束時, startIndex所指的即為滿足條件的元素下標.
需要注意的是, 最后返回的時候,需要比較startIndex和最初endIndex的大小,如果 startIndex > endIndex, 說明查找失敗,沒有滿足條件的元素.

實現

int BinarySearch::searchInternal(const std::vector<int>& datas,
                                 int startIndex,
                                 int endIndex,
                                 const int dest)
{
    int ret = -1; 
    int end = endIndex;
    while (startIndex <= endIndex)
    {   
        int midIndex = startIndex + (endIndex - startIndex) / 2;
        if (datas[midIndex] >= dest)
        {   
            endIndex = midIndex - 1;
        }   
        else
        {   
            startIndex = midIndex + 1;
        }   
    }   
    return startIndex <= end ? startIndex : -1; 
}

Case 3: 查找第一個大于某個數的下標

當中間下標數小于等于目標數時, 繼續查找右邊區間.
當中間下標數大于目標數時, 繼續查找左邊區間.
當startIndex > endIndex時, 結束查找, 此時startIndex所指的數字即為查找的數字下標, 如果startIndex大于起始endIndex則查找失敗,返回 -1.

int BinarySearch::searchInternal(const std::vector<int>& datas,
                                 int startIndex,
                                 int endIndex,
                                 const int dest)
{
    int ret = -1; 
    int end = endIndex;
    while (startIndex <= endIndex)
    {   
        int midIndex = startIndex + (endIndex - startIndex) / 2;
        if (datas[midIndex] > dest)
        {   
            endIndex = midIndex - 1;
        }   
        else
        {   
            startIndex = midIndex + 1;
        }   
    }   
    return startIndex <= end ? startIndex : -1; 
}

擴展題型

擴展1: 查找數組中某個數的位置的最小下標, 沒有則返回-1

思路參考Case 2. 先找到第一個大于或者等于目標數的數字, 判斷該數字是否等于目標數, 如果等于目標數, 則返回該數字的下標, 否則返回-1.

擴展2: 查找數組中某個數的位置的最大下標, 沒有則返回-1

思路參考Case 3. 先找到第一個大于目標數的數字, 判斷該數字前面一個下標的數字是否等于目標數, 如果等于目標數, 則返回該數字的下標, 否則返回-1.

擴展3: 查找數組中小于某個數的最大下標, 沒有返回-1.

思路參考Case 2. 先找到第一個大于或者等于目標數的數字, 然后判斷前一個下標是否合法, 如果合法,則返回, 否則返回-1.

擴展4: 查找數組中某個數的出現次數

思路: 使用Case 2求出下界, 使用Case 3求出上界, 然后用上界 - 下界 即為某個數出現的次數.
但是需要注意返回值, 當越界時, 不能返回-1, 而是返回越界值來計算差值.

參考資料:
http://blog.csdn.net/yefengzhichen/article/details/52372407

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容