Given a sorted array of integers, 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].
public int[] searchRange(int[] nums, int target) {
int low = 0, high = nums.length - 1, temp = -1;
int result[] = new int[2];
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
temp = mid;
break;
}
if (nums[mid] > target)
high = mid - 1;
if (nums[mid] < target)
low = mid + 1;
}
if (temp == -1) {
Arrays.fill(result, -1);
return result;
}
int tmp = temp;
while (tmp > 0 && target == nums[tmp - 1])
tmp--;
while (temp < nums.length-1 && target == nums[temp + 1])
temp++;
result[0] = tmp;
result[1] = temp;
return result;
}
上discuss看了简单一些的方法吧,分享下。
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
if (nums[left] == target && nums[right] == target)
return new int[] { left, right };
else if (nums[left] != target)
left++;
else
right--;
} else if (nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return new int[] { -1, -1 };
}