当前位置:网站首页>4 搜索插入位置
4 搜索插入位置
2022-07-17 00:07:00 【DHU杨骅麟(紫外线过敏)】
4 搜索插入位置
作者: Turbo时间限制: 1S章节: 课程设计
问题描述 :
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1:
输入:
4
1 3 5 6
5
输出: 2
示例 2:
输入:
4
1 3 5 6
2
输出: 1
输入说明 :
输入三行:
第一行输入一个整数n表示数组nums的长度。
第二行输入n个整数表示数组nums的元素。
第三行输入一个整数表示需要查找的目标值target.
提示:
1 <= n <= 10^4
-10^4 <= nums[i] <= 10^4
nums 为 无重复元素 的 升序 排列数组
-10^4 <= target <= 10^4
输出说明 :
输出一个整数表示结果。
输入范例 :
4
1 3 5 6
7
输出范例 :
4
#include<iostream>
using namespace std;
void search(int arr[],int target,int length)
{
int left = 0;
int right = length - 1;
if (arr[length - 1] < target)
{
cout << length;
length++;
return;
}
else if (arr[0] > target)
{
cout << 0;
length++;
return;
}
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == target)
{
cout<<mid;
return;
}
else if (arr[mid] < target)
{
left = mid + 1;
}
else if (arr[mid] > target)
{
right = mid - 1;
}
cout<< left;
return;
}
}
int main()
{
int arr[100000];
int length = 0;
cin >> length;
for (int i = 0; i < length; i++)
{
cin >> arr[i];
}
int target = 0;
cin >> target;
search(arr, target, length);
return 0;
}边栏推荐
- Yii2反序列化漏洞复现
- 今天的码农女孩总结了关于npm包管理和url模块的笔记
- Uni scroll view pull-down refresh
- 今天的码农女孩总结了jQuery处理缓存的方法和事件委托方法的区别的笔记
- Text indent in uniapp doesn't work, and the indentation in the first line of uniapp doesn't work. How to solve it?
- Use leaflet to copy the original shentiwa Mega map to make a diary
- uni-app微信小程序——商城(8)——订单详情
- The difference between let and VaR
- Use bat to automatically execute CMD commands (multiple commands or a single command)
- iptables和snort基本配置
猜你喜欢
随机推荐
Computed and watch, watcheffect
今天的码农女孩学习了关于nodejs和REPL 交互式解释器的知识
文章不会一直保持VIP收费 过一段时间 会开放
Uniapp development, upload pictures in the app and send them directly to OSS
Uni app wechat official account (1) - Web page authorization login
uni-app微信小程序——商城(6)——我的主页
03_el与data的两种写法
9 无人机方阵
15 设计电影租借系统
软件漏洞分析入门(四)
uni-app微信小程序——商城(7)——商品详情
Uniapp calls the map to query the location and mark the location
Yii2反序列化漏洞复现
Uni app wechat applet - Mall (8) - order details
记一次用canvas做出腾讯云首页banner流光效果的经历
el-date-picker时间范围控制
Determine whether the two timestamps are the same day
2022年暑假ACM热身练习2(总结)
Registry hijacking triggers malicious programs
微信推送-模版消息参数配置









