方法一
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;
}
}
方法二:
https://www.cnblogs.com/kyoner/p/11080078.html
参考链接
https://blog.csdn.net/lonelymanontheway/article/details/80330560
http://www.mamicode.com/info-detail-184617.html