public static void main(String[] args){
int[] arr2 = {1, 2, 3, 7, 8, 8, 8, 8, 9, 10, 18};
int endEqualByHzz = findEndLessEqualByHzz(arr2, 11);
System.out.println(endEqualByHzz);
}
//找到第一个匹配的值
static int findFirstEqualByHzz(int[] array, int key) {
int left = 0;
int right = array.length - 1;
int mid = 0;
while (left <= right) {
mid = left + ((right - left) >> 1);
if (array[mid] == key) {
if (array[mid - 1] != key) {
return mid;
} else {
right = mid - 1;
}
} else if (array[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
//找最后一个值与给定的值相等
static int findEndEqualByHzz(int[] array, int key) {
int left = 0;
int right = array.length - 1;
int mid = 0;
while (left <= right) {
mid = left + ((right - left) >> 1);
if (array[mid] == key) {
if (array[mid + 1] != key) {
return mid;
} else {
left = mid + 1;
}
} else if (array[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
//查找第一个大于等于给定值
static int findFirstMoreEqualByHzz(int[] array, int key) {
int left = 0;
int right = array.length - 1;
int mid = 0;
while (left <= right) {
mid = left + ((right - left) >> 1);
if (array[mid] >= key) {//大于等于
if (array[mid - 1] < key) {//边界范围 确定限制条件为 "第一个" ,前面一个元素小于要查找的值 value,那 a[mid] 就是我们要找的元素。
return mid;
} else {
right = mid - 1;
}
} else {
left = mid + 1;
}
}
return -1;
}
//查找最后一个小于等于给定值的元素
static int findEndLessEqualByHzz(int[] array, int key) {
int left = 0;
int right = array.length - 1;
int mid = 0;
while (left <= right) {
mid = left + ((right - left) >> 1);
if (array[mid] <= key) {//大于等于
if (array[mid + 1] > key) {//边界范围 确定限制条件为 "最后一个" ,后边的元素大于给定的值 那么前边的元素就是小于等于给定的值
return mid;
} else {
left = mid + 1;
}
} else {
right = mid - 1;
}
}
return -1;
}