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) {
// write your code here
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
if (A == null) return result;
int length = A.length;
if (length == 0) return result;
int start = 0;
int end = length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) end = mid;
else if (A[mid] > target) end = mid;
else start = mid;
}
if (A[start] == target) result[0] = start;
else if (A[end] == target) result[0] = end;
else return result;
start = 0;
end = length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) start = mid;
else if (A[mid] > target) end = mid;
else start = mid;
}
if (A[end] == target) result[1] = end;
else result[1] = start;
return result;
}
}
61 Search For A Range
最后編輯于 :
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 題目:Given an array of integers sorted in ascending order, ...
- 題目 Given an array of integers sorted in ascending order, ...
- Given an array of integers sorted in ascending order, fin...
- 最近因需要實(shí)現(xiàn)一個(gè)標(biāo)簽類(lèi)的 demo, 需要支持拖拽重排, 首先想到的便是 collectionView, 并且很...
- 你有沒(méi)有問(wèn)過(guò)自己這樣一個(gè)問(wèn)題,人生在世大家都在憑著什么在打拼?憑借什么在中國(guó)這種資源稀少人口眾多的國(guó)家,拼出一...