LeetCode Search for a Range (二分查找)
题意
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
给定一个有序数组和一个目标值,查找出目标值在数组中出现的发生下标区域。时间复杂度要求log(N)。
解法
刚开始以为下标也需要用二分来查找,但看讨论发现大家都是找出目标值然后再向两边搜索-_-b,这样做的话,最差的情况下(数组里的数全都一样)就是O(N)了,但是也能过。
class Solution
{
public:
vector<int> searchRange(vector<int>& nums, int target)
{
int left = 0;
int right = nums.size() - 1;
int index_a = -1;
int index_b = -1;
int index = 0;
bool flag = false;
while(left <= right)
{
int mid = (left + right) >> 1;
if(nums[mid] == target)
{
flag = true;
index = mid;
break;
}
else
if(nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
if(flag)
index_a = index;
while(index_a >= 1 && nums[index_a - 1] == target)
index_a --;
if(flag)
index_b = index;
while(index_b < nums.size() - 1 && nums[index_b + 1] == target)
index_b ++;
vector<int> rt = {index_a,index_b};
return rt;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?