搜索區(qū)間

描述

給定一個(gè)包含 n 個(gè)整數(shù)的排序數(shù)組,找出給定目標(biāo)值 target 的起始和結(jié)束位置。
如果目標(biāo)值不在數(shù)組中,則返回[-1, -1]

樣例

給出[5, 7, 7, 8, 8, 10]和目標(biāo)值 target=8,
返回[3, 4]
給出[1]和目標(biāo)值target=1,
返回[0,0]

相關(guān)題目

目標(biāo)出現(xiàn)次數(shù)總和

代碼實(shí)現(xiàn)

public class Solution {
    /** 
     *@param A : an integer sorted array
     *@param target :  an integer to be inserted
     *return : a list of length 2, [index1, index2]
     */
    public int[] searchRange(int[] A, int target) {
        int[] result = new int[2];
        if (A == null || A.length == 0) {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
        if (A.length == 1 && A[0] == target) {
            result[0] = 0;
            result[1] = 0;
            return result;
        }
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] < target) {
                start = mid;
            } else  {
                end = mid;
            } 
        }
        if (A[start] == target) {
            result[0] = start;
            for (int i = A.length-1; i >= start; i--) {
                if (A[i] == target) {
                    result[1] = i;
                    return result;
                }
            }
            result[1] = start;
            return result;
        }
        else if (A[end] == target) {
            result[0] = end;
            for (int i = A.length-1; i >= end; i--) {
                if (A[i] == target) {
                    result[1] = i;
                    return result;
                }
            }
            result[1] = end;
            return result;
        } else {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
    }
}

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

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

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