Problem 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, ten] and target value 8,
return [3, 4].
Find a range of occurrences of a number in a sorted array
Algorithmic thinking
Two-point lookup to the number of targets before and after order lookup
Algorithm implementation
Public classSolution { Public int[]Searchrange(int[] Nums,intTarget) {int[] result =New int[] { -1, -1};if(Nums = =NULL|| Nums.length = =0)returnResultintloc = Arrays.binarysearch (nums, target);if(Loc <0)returnResultElse{inti = loc, j = loc; while(i>=0&&nums[i] = = target) {i--;} while(J<nums.length&&nums[j] = = target) {j + +;} result[0] = i+1; result[1] = J1; }returnResult }}
Algorithm time
Algorithm time is two minutes to find time
T (n) =o (LOGN)
But if all the numbers are the same, the lookup time is O (1), the sequential lookup time is O (n), so the worst case is O (n)
Demo results
Public Static void Main(string[] args) {intResult[] =New int[] { -1, -1};int[] arr = {1, at, the, the, the, the, the, Wu, $, the}; result = Searchrange (arr, $); System. out. println (result[0] +":"+ result[1]); }
8:8
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode" Search for a Range