题目描述:
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 class Solution { public int[] searchRange(int[] nums, int target) { int[] result = { -1, -1 }; int left = 0; int right = nums.length - 1; int mid, low, high; if (target > nums[right] || target < nums[left]) return result; while (left <= right) { mid = (left + right) / 2; if (nums[mid] == target) { low = mid; high = mid; while (low >= 0 && nums[low] == target) low--; result[0] = low + 1; while (high < nums.length && nums[high] == target) high++; result[1] = high - 1;
return result; } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return result; } }