Question
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]
.
Solution
Use binary search, first, find left position, then, find right position.
1 Public classSolution {2 Public int[] Searchrange (int[] Nums,inttarget) {3 int[] result =New int[2];4Result[0] = 1;5RESULT[1] = 1;6 if(Nums = =NULL|| Nums.length < 1)7 returnresult;8 intStart = 0, end = nums.length-1, Mid, first, last;9 //Find first position of targetTen while(Start + 1 <end) { OneMid = (End-start)/2 +start; A if(Nums[mid] >=target) -End =mid; - Else theStart =mid; - } - if(Nums[start] = =target) -Result[0] =start; + Else if(Nums[end] = =target) -Result[0] =end; + A //Find last position of target atStart = 0; -End = Nums.length-1; - while(Start + 1 <end) { -Mid = (End-start)/2 +start; - if(Nums[mid] <=target) -Start =mid; in Else -End =mid; to } + if(Nums[end] = =target) -RESULT[1] =end; the Else if(Nums[start] = =target) *RESULT[1] =start; $ returnresult;Panax Notoginseng } -}
Search for a Range solution