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]
.public class Solution {
public int[] searchRange(int[] A, int target) {
int[] ret = {-1, -1};
if(A==null || A.length==0 || target<A[0] || target>A[A.length-1]) {
return ret;
}
int start = 0;
int end = A.length-1;
while(start<=end && !(ret[0]!=-1 && ret[1]!=-1)) {
int mid = (start+end)/2;
if(A[mid]==target) {
end = mid;
start = mid;
while(end<A.length && A[end]==A[mid]) {
end++;
}
while(start>=0 && A[start]==A[mid]) {
start--;
}
ret[0] = start + 1;
ret[1] = end - 1;
} else if(A[mid]<target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return ret;
}
}
==========
public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = {nums.length, -1};
search(nums, 0, nums.length - 1, target, res);
if (res[0] == nums.length) {
res[0] = -1;
}
return res;
}
private void search(int[] nums, int s, int e, int target, int[] range) {
if (s <= e) {
int m = (s + e) / 2;
if (target == nums[m]) {
range[0] = Math.min(range[0], m);
search(nums, s, m - 1, target, range);
range[1] = Math.max(range[1], m);
search(nums, m + 1, e, target, range);
} else if (target < nums[m]) {
search(nums, s, m - 1, target, range);
} else {
search(nums, m + 1, e, target, range);
}
}
}
}
===========
public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = helper(nums, 0, nums.length - 1, target);
return res;
}
private int[] helper(int[] nums, int s, int e, int target) {
int[] res = {-1, -1};
while (s <= e) {
int m = (s + e) / 2;
if (nums[m] > target) {
e = m - 1;
} else if (nums[m] < target) {
s = m + 1;
} else {
int[] left = helper(nums, s, m - 1, target);
res[0] = left[0] == -1 ? m : left[0];
int[] right = helper(nums, m + 1, e, target);
res[1] = right[1] == -1 ? m : right[1];
break;
}
}
return res;
}
}
=====
public class Solution {
public int[] searchRange(int[] nums, int target) {
return find(nums, target, 0, nums.length - 1, true, true);
}
private int[] find(int[] nums, int target, int s, int e, boolean findleft, boolean findright) {
int[] res = {-1, -1};
while (s <= e) {
int m = s + (e - s) / 2;
if (nums[m] == target) {
res[0] = m;
res[1] = m;
if (findleft) {
int[] left = find(nums, target, s, m - 1, true, false);
if (left[0] != -1) res[0] = left[0];
}
if (findright) {
int[] right = find(nums, target, m + 1, e, false, true);
if (right[0] != -1) res[1] = right[1];
}
break;
} else if (nums[m] < target) {
s = m + 1;
} else {
e = m - 1;
}
}
return res;
}
}
没有评论:
发表评论