Title Description:
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O(log n).
If the target is not a found in the array, return [-1, -1] .
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
Return [3, 4] .
The idea of knot problem:
Using the dichotomy method, if it is found, it spreads from this position to both sides until it reaches the boundary of the target value.
The code is as follows:
public class Solution {public int[] Searchrange (int[] nums, int target) {int[] result = {-1,-1};int left = 0;int r ight = Nums.length-1;int Mid, low, high;if (Target > nums[right] | | target < NUMS[LEFT]) return Result;while <= right) {mid = (left + right)/2;if (Nums[mid] = = target) {low = Mid;high = Mid;while (Low >= 0 && nums[l OW] = = target) low--;result[0] = low + 1;while (High < nums.length && Nums[high] = = target) high++;result[1] = Hi Gh-1;
return result;} else if (Nums[mid] > target) {right = Mid-1;} else {left = mid + 1;}} return result;}}
Java [Leetcode 34]search for a Range