LintCode_060_搜索插入位置
来源:互联网 发布:淘宝食品店铺装修 编辑:程序博客网 时间:2024/05/17 08:45
问题描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
求解
经典的“二分查找”在未找到匹配值时,一般返回 -1,这里在经典算法上稍加改造便能符合题目需求
class Solution{ public: int searchInsert(vector<int> &A, int target) { int left = 0; int right = A.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (target < A[mid]) { right = mid - 1; } else if (A[mid] < target) { left = mid + 1; } else { return mid; } } return left; }};
我们还有STL这个“外挂”,只需一行代码就能解决问题
class Solution2{ public: int searchInsert(vector<int> &A, int target) { return lower_bound(A.begin(), A.end(), target) - A.begin(); }};
阅读全文
0 0
- LintCode_060_搜索插入位置
- 题目:搜索插入位置
- LintCode : 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- lintcode ----搜索插入位置
- LintCode : 插入搜索位置
- 搜索插入位置
- Lintcode 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- lintcode:搜索插入位置
- Lintcode搜索插入位置
- lintCode 搜索插入位置
- 60. 搜索插入位置
- 【lintcode笔记】搜索插入位置
- 联想高校AI精英挑战赛争霸浙江大学,“管道医生”项目晋级赛摘得桂冠
- HDU-1114 Piggy-Bank 完全背包的灵活运用
- css知多少(2)——学习css的思路
- stm32_006_STM32F103VCT6资源
- TIM
- LintCode_060_搜索插入位置
- 基于git的代码版本管理规范及流程-简版
- 求一个3*3矩阵对角线元素之和。
- Python,对字符串操作
- 经典排序算法
- iscsi
- 数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历
- 模板类与友元函数:关于LNK1120和LNK2019报错
- 马未都谈教育