2023每日刷题(六)
Leetcode—34.在排序数组中查找元素的第一个和最后一个位置
实现代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int lower_bound(int *arr, int numsSize, int target) {
// 左闭右开区间[left, target)
int left = 0, right = numsSize;
int mid;
while(left < right) {
mid = left + (right - left) / 2;
if(arr[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
int *ans = (int *)malloc(sizeof(int) * 2);
*returnSize = 2;
ans[0] = -1;
ans[1] = -1;
int left = lower_bound(nums, numsSize, target);
int right = lower_bound(nums, numsSize, target + 1) - 1;
if(numsSize != 0 && left != numsSize && nums[left] == target) {
ans[0] = left;
ans[1] = right;
}
return ans;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!