My code:
public class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0)
return null;
int[] result = new int[2];
int lo = 0;
int hi = nums.length - 1;
BinarySearch(lo, hi, target, nums, result);
return result;
}
private void BinarySearch(int lo, int hi, int target, int[] nums, int[] result) {
if (lo > hi) {
result[0] = -1;
result[1] = -1;
return;
}
int mid = (lo + hi) / 2;
if (target > nums[mid]) {
while (mid + 1 < nums.length && nums[mid + 1] == nums[mid])
mid++;
BinarySearch(mid + 1, hi, target, nums, result);
}
else if (target < nums[mid]) {
while (mid - 1 >= 0 && nums[mid - 1] == nums[mid])
mid--;
BinarySearch(lo, mid - 1, target, nums, result);
}
else {
int i = mid;
while (i + 1 < nums.length && nums[i + 1] == nums[i])
i++;
result[1] = i;
i = mid;
while (i - 1 >= 0 && nums[i - 1] == nums[i])
i--;
result[0] = i;
}
}
}
My test result:
这道题目没什么大的难度。主要就是其中需要用 while循环过滤掉那些重复出现的数字,之前一道题目中出现过一种方法。具体忘了。
**
总结:binary search in range
**
Anyway, Good luck, Richardo!
原先的做法并不能保证严格的O(log n).
还是得用两次bianry search
第一次,搜索 target 出现的左边界,相比于BS来说,变化在于,
when nums[mid] == target:
mid--;
第二次,搜索target出现的右边界,相比于BS来说,变化在于:
when nums[mid] == target:
mid++;
而且,最后给ret赋值的时候,得注意判断,
begin是否 <nums.length
end时候 >= 0
Anyway, Good luck, Richardo! -- 09/03/2016
My code:
public class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new int[]{-1, -1};
}
int[] ret = new int[2];
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
end = mid;
}
else if (nums[mid] < target) {
start = mid;
}
else {
end = mid;
}
}
if (nums[start] == target) {
ret[0] = start;
}
else if (nums[end] == target) {
ret[0] = end;
}
else {
ret[0] = -1;
ret[1] = -1;
return ret;
}
start = 0;
end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
start = mid;
}
else if (nums[mid] > target) {
end = mid;
}
else {
start = mid;
}
}
if (nums[end] == target) {
ret[1] = end;
}
else if (nums[start] == target) {
ret[1] = start;
}
else {
ret[0] = -1;
ret[1] = -1;
return ret;
}
return ret;
}
}
reference:
http://www.jiuzhang.com/solutions/search-for-a-range/
Anyway, Good luck, Richardo! -- 10/16/2016