[Leetcode] search insert position 寻找插入位置
2024-09-27 09:45:10
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
题意:在已排序的数组中查找给定数字,若有,返回下标,没有,则返回插入位置
思路:题意的要求应该理解成,应该返回的是第一个不小于目标值的下标。所以用二分查找即可。详情可见我之前的博客关于二分查找的总结。代码如下:
class Solution {
public:
int searchInsert(int A[], int n, int target)
{
int lo=,hi=n;
while(lo<hi)
{
int mid=lo+((hi-lo)>>);
if(A[mid]<target)
lo=mid+;
else
hi=mid;
}
return hi;
}
};
最新文章
- JS 生成GUID 方法
- C++ 虚函数,纯虚函数的一些问题
- 音频文件解析(一):WAV格式文件头部解析
- Hibernate和Mybatis的对比
- 转载:开发者眼中最好的 22 款 GUI 测试工具
- WCF入门(22)
- eclipse 每次切换工作空间都要重新配置
- paip.android 手机输入法制造大法
- mongodb 新建用户 -摘自网络
- Android 各个版本WebView
- C# 创建验证码图片
- HDU 5428 The Factor (素因数分解)
- ETL实践--kettle转到hive
- web 服务器、PHP、数据库、浏览器是如何实现动态网站的
- tensorflow-Inception-v3模型训练自己的数据代码示例
- Linux配置防火墙端口 8080端口
- MVC AOP解决JsonResult返回json时间格式
- 微信小程序 自定义单选复选按钮组的实现(用于实现购物车产品列表功能)
- LeetCode-Microsoft-Clone Graph
- node 本地静态服务器
热门文章
- “腾讯WeTest助力《龙珠直播》盘点APP质量问题”
- system_Class类说明文档
- 打印队列 (Printer Queue,ACM/ICPC NWERC 2006,UVA12100)
- 从零开始的Python学习Episode 1
- codeforces 319B Psychos in a Line(模拟)
- 自测之Lesson13:共享内存
- Greedy Gift Givers 贪婪的送礼者
- “Hello World!”团队召开的第十二次会议
- 第二次作业 编程题 PAT 1001A+B Format
- TCP系列13—重传—3、协议中RTO计算和RTO定时器维护