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
return
Given
[5, 7, 7, 8, 8, 10]
and target value 8,return
[3, 4]
.Solution:
Apply two binary searches.
The first search is to find the first occurrence of target.
If we find a match, we include it and search to the left.
The second search is to find the last occurrence of target.
If we find a match, we include it and search to the right.
The time complexity is O(logn) and the space complexity is O(n).
Code:
public class Solution { public int[] searchRange(int[] nums, int target) { if (nums == null || nums.length == 0) { return new int[] {-1, -1}; } 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 { start = mid; } } int first = -1; int last = -1; if (nums[start] == target) { first = start; } else if (nums[end] == target) { first = end; } else { return new int[] {first, last}; } start = 0; end = nums.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] <= target) { start = mid; } else { end = mid; } } if (nums[end] == target) { last = end; } else if (nums[start] == target) { last = start; } return new int[] {first, last}; } }