LeetCode 34 Search for a Range (有序数组中查找给定数字的起止下标)

时间:2022-10-20 14:53:18

 
Problem: 在已知递减排序的数组中,查找到给定数字的起止下标
 
采用两遍扫描;
第一遍扫描得到给定数字的起始下标,(从下标i==0开始到nums.lenght-1)
第二遍扫描从第一遍扫描得到的下标开始进行扫描 
 
参考代码:
package leetcode_50;

/***
*
* @author pengfei_zheng
* 数组中找到target起止下标
*/
public class Solution34 {
public static int[] searchRange(int[] nums, int target) { int start = 0, end = nums.length-1; int []ans = {-1,-1}; while(start<=end){
int mid = (start + end)/2;
if(nums[mid] >= target)
end = mid - 1;
else
start = mid + 1;
if(nums[mid]==target){
ans[0]=mid;
}
}
start = ans[0]==-1 ? 0 : ans[0];
end=nums.length-1;
while(start<=end){
int mid = (start+end)/2;
if(nums[mid]<=target)
start = mid + 1;
else
end = mid - 1;
if(nums[mid]==target)
ans[1]=mid;
}
return ans;
}
public static void main(String[]args){
int []nums = {5, 7, 7, 8, 8, 10};
int []ans = {0};
ans = searchRange(nums,8);
for(int item:ans){
System.out.print(item+" ");
}
}
}