当前位置:网站首页>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;
}边栏推荐
- 7 矩阵中战斗力最弱的 K 行
- Replace special characters in URL (%e2%80%8b)
- 04-BTC-实现
- JSX syntax
- The difference between let and VaR
- Solve the flashing of the menu switch at the bottom of applet customization
- Use bat to automatically execute CMD commands (multiple commands or a single command)
- qs模块是?
- uni-app微信小程序——商城(7)——商品详情
- 今天的码农女孩做了关于生命周期的笔记以及动态时钟的练习
猜你喜欢

自己封装的风格化的开关卡片组件

单页面应用 SPA 和多页面应用 MPA

红日安全靶场3

uni-app微信小程序——商城(3)——商城主页

Summary of Applied Cryptography

Page layout - three column layout solution

The applet is embedded in the web page, jumps to the applet and transmits parameters. The wechat applet realizes the authorization of official account to obtain openid

uni-app微信小程序——商城(6)——我的主页

Self encapsulated stylized switch card assembly

XXX packages are looking for funding run `npm fund` for details解决方法
随机推荐
15 数据流的第 K 大数值
02_ Data binding
04-BTC-实现
Express中间件的分类及使用
V-cloak and v-bind bind bind classes
let和const、let、const和var的区别
XSS simple summary
Uni block button multiple clicks button multiple clicks
PCRE bypasses regular
今天的码农女孩学习了关于事件操作和ref属性的笔记并做了表单双向绑定的练习
If the website is hacked, what if you jump to other websites through Baidu / Sogou and other search keywords?
El form special character verification
[SWPU 2019] network TTL encryption and some related knowledge
Uniapp development, upload pictures in the app and send them directly to OSS
03-BTC-协议
uni-app微信公众号(5)——新增、修改地址
02_数据绑定
Express的使用方法,路由的匹配与使用
uni-app微信小程序——商城(7)——商品详情
[AHU2021校内赛] ez-injection