下面介绍两个子问题。
给定一个 nums[]. target, 求 该数组中,大于等于target的最小值的index
private int ceil(int[] nums, int target) {
int begin = 0;
int end = nums.length - 1;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
if (nums[mid] > target) {
end = mid - 1;
}
else if (nums[mid] < target) {
begin = mid + 1;
}
else {
return mid;
}
}
return begin;
}
求小于等于target 的最大数的index
private int floor(int[] nums, int target) {
int begin = 0;
int end = nums.length - 1;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
if (nums[mid] > target) {
end = mid - 1;
}
else if (nums[mid] < target) {
begin = mid + 1;
}
else {
return mid;
}
}
return end;
}
感觉会经常用,记住了。
网友评论