int lowerBound(int* nums, int numsSize, int target) { //注意left和right的初始值必须是left = 0, right = numsSzie, 因为返回的位置可能是[0,numsSize] int left = 0; int right = numsSize; int mid; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] >= target) right = mid; else left = mid + 1; } return left; } int upperBound(int* nums, int numsSize, int target) { int left = 0; int right = numsSize; int mid; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] <= target) left = mid + 1; else right = mid; } return left; }
时间: 2024-11-07 00:13:39