首页 技术 正文
技术 2022年11月19日
0 收藏 394 点赞 4,905 浏览 885 个字

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

问题:给定一个已排序数组和一个整数,若整数已在数组中则返回在数组中的下标,否则返回应当插入的位置。

对一个已排序数组进行搜索,很自然地会想到二分搜索(Binary Search),毕竟是经典场景。这道题也确实是二分搜索的一个简单应用。

之所以记录这道题目,是感觉二分搜索和之前做的 双指针法 two pointers ,或者是滑动窗口算法(sliding window) 有些相似。

二分搜索,实际上,可以理解为每次减半的滑动窗口算法,来定位最终的目标位置。

而滑动窗口算法,另一个典型场景就是求解最大/最小 的连续子数组,或连续子字符串。在另一篇博文有介绍:Minimum Size Subarray Sum 。

 int searchInsert(vector<int>& nums, int target) {     if (nums.size() == ) {
return ;
} if (nums.size() == ) {
return (nums[] < target) ? : ;
} int l = ;
int r = (int)nums.size() - ; while (l < r) { if (l + == r) {
if ( target <= nums[l]) {
return l;
}
else if (target <= nums[r]){
return r;
}
else{
return r+;
}
} int mid = (l + r) / ; if (nums[mid] == target) {
return mid;
} if (nums[mid] < target) {
l = mid;
}else{
r = mid;
}
} // 实际上无法执行到这里,在前面必然有 return.
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,112
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,585
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922