Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]
这道题参考了博文http://blog.youkuaiyun.com/linhuanmars/article/details/20593391
这篇文章讲得很好,尤其是左右下标滑动找到结果的方式,很棒!
class Solution {
public int[] searchRange(int[] nums, int target) {
int ll = 0;
int lr = nums.length - 1;
int rl = 0;
int rr = nums.length - 1;
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
int m1 = 0;
int m2= 0;
if(nums == null || nums.length == 0){
return result;
}
while(ll <= lr){
m1 = (ll + lr)/2;
if(nums[m1] < target){
ll = m1 + 1;
}else{
lr = m1 -1;
}
}
while(rl <= rr){
m2 = (rl + rr)/2;
if(nums[m2] <= target){
rl = m2 +1;
}else{
rr = m2 -1;
}
}
if(ll <= rr){
result[0] = ll;
result[1] = rr;
}
return result;
}
}
本文介绍了一种算法,可在已排序的整数数组中查找给定目标值的起始和结束位置,采用二分查找法实现O(log n)的时间复杂度。若未找到目标值,则返回[-1,-1]。
711

被折叠的 条评论
为什么被折叠?



