Problem Description: Given an ordered sequence, the starting and ending positions of the specified element are found. Example: 1234555, 5, start 4 end 6
Algorithm analysis: In fact, is a two-point search for the use. But the special is not to find an element, but to find the subscript. That is, when Nums[mid]=target, the left and right elements of mid are analyzed.
Public int[] Searchrange (int[] Nums,inttarget) { if(Nums = =NULL|| Nums.length = = 0) { return NULL; } int[] arr = { -1,-1}; BinarySearch (Nums,0, Nums.length-1, Target, arr); returnarr; } Public voidBinarySearch (int[] Nums,intLeftintRightintTargetint[] arr) { intMid = (left + right)/2; if(Left >Right ) { return; } if(Nums[left] = = Target && Nums[right] = = target)//Special Cases{arr[0] =Left ; arr[1] =Right ; return; } if(Nums[mid] = =target) { intTempl = Mid, Tempr =mid; while(Templ>=left && nums[templ]==target) {Templ--; } arr[0] = templ+1; while(Tempr<=right && nums[tempr]==target) {TEMPR++; } arr[1] = Tempr-1; } Else if(Nums[mid] <target) {BinarySearch (nums, Mid+ 1, right, target, arr); } Else{BinarySearch (Nums, left, mid-1, Target, arr); } }
Search for a range to find the starting and ending positions of the specified element in an ordered sequence that may have repeating elements