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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 题目: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...
- 最近因需要实现一个标签类的 demo, 需要支持拖拽重排, 首先想到的便是 collectionView, 并且很...