算法求一个数字在给定的已排序数组中出现的起始终止索引号

【算法求一个数字在给定的已排序数组中出现的起始终止索引号】贵有恒,何必三更起、五更眠、最无益,只怕一日曝、十日寒。这篇文章主要讲述算法求一个数字在给定的已排序数组中出现的起始终止索引号相关的知识,希望能为你提供帮助。
方法一

public class findthefirstandlast
public int finderfirstandlast(int[] arr, int target)
int first = findfirstindex(arr, target);
int last = findlastindex(arr, target);
System.out.println(first);
System.out.println(last);
return findlastindex(arr, target) - findfirstindex(arr, target);


public int findfirstindex(int[] arr, int target)
int left = 0;
int right = arr.length - 1;
int mid;
while (left < = right)
mid = (left + right) / 2;
if (arr[mid] < target)
left = mid + 1;
else if (arr[mid] > target)
right = mid - 1;

else
if ( mid == 0 || arr[mid - 1] != target)
return mid;

right = mid - 1;


return -1;


public int findlastindex(int[] arr, int target)
int left = 0;
int right = arr.length - 1;
int mid;
while (left < = right)
mid = (left + right) / 2;
if (arr[mid] < target)
left = mid + 1;
else if (arr[mid] > target)
right = mid - 1;

else
if (mid == arr.length - 1 || arr[mid + 1] != target)
return mid;

left = mid + 1;


return -1;


?
参考链接http://www.mamicode.com/info-detail-184617.html



    推荐阅读