title Link: https://leetcode.com/problems/search-for-a-range/?tab=Description
Problem: Finds the start and end subscript of a given number in an array known as descending orderUse two times scanning; the first scan obtains the starting subscript for a given number (from subscript i==0 to Nums.lenght-1) The second pass scans the reference code starting with the subscript from the first scan:
Packageleetcode_50;/*** * * @authorPengfei_zheng * Find target starting and ending subscript in array*/ Public classSolution34 { Public Static int[] Searchrange (int[] Nums,inttarget) { intStart = 0, end = nums.length-1; int[]ans = { -1,-1}; while(start<=end) { intMid = (start + end)/2; if(Nums[mid] >=target) End= Mid-1; ElseStart= Mid + 1; if(nums[mid]==target) {ans[0]=mid; }} Start= Ans[0]==-1? 0:ans[0]; End=nums.length-1; while(start<=end) { intMid = (start+end)/2; if(nums[mid]<=target) Start= Mid + 1; ElseEnd= Mid-1; if(nums[mid]==target) ans[1]=mid; } returnans; } Public Static voidMain (String[]args) {int[]nums = {5, 7, 7, 8, 8, 10}; int[]ans = {0}; Ans= Searchrange (nums,8); for(intItem:ans) {System.out.print (item+" "); } }}
Leetcode Search for a Range (to find the starting and ending subscript for a given number in an ordered array)