Search for a Range

Search for a Range.png

===================== 解題思路 =====================

這題是個綜合 first position && last position 的題目 基本就是先找 first position 如果沒找到代表根本沒有 target 在裡面 直接回傳 {-1,-1} 如果找到就先存好 res[0] 的值為 first position 接著再跑 last position (特別注意要記得 reset left 跟 right 的值)

===================== C++ code ====================

<pre><code>
class Solution {

/** 
 *@param A : an integer sorted array
 *@param target :  an integer to be inserted
 *return : a list of length 2, [index1, index2]
 */

public:

vector<int> searchRange(vector<int> &A, int target) {
    // find the first position
    vector<int> res(2, -1);
    if(A.size() == 0) return res;
    int left = 0, right = A.size() - 1;
    while(left + 1 < right)
    {
        int mid = left + (right - left) / 2;
        if(A[mid] >= target) right = mid;
        else left = mid;
    }
    if(A[left] != target && A[right] != target) return res;
    res[0] = A[left] == target? left : right;
    
    //find the last position
    left = 0;
    right = A.size() - 1;
    while(left + 1 < right)
    {
        int mid = left + (right - left) / 2;
        if(A[mid] <= target) left = mid;
        else right = mid;
    }
    res[1] = A[right] == target? right : left;
    return res;
}

};
<code><pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容