LintCode_060_搜索插入位置
2017-12-06 22:34
369 查看
问题描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。你可以假设在数组中无重复元素。
样例
[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(); } };
相关文章推荐
- LintCode_060_搜索插入位置
- Lintcode搜索插入位置
- lintcode:搜索插入位置
- lintcode 容易题:Search Insert Position 搜索插入位置
- LintCode 60. 搜索插入位置
- lintcode python 容易 60.搜索插入位置
- LintCode 60 搜索插入位置
- LintCode : 搜索插入位置
- lintcode&九章算法——No.60 搜索插入位置 ? 待解决
- Leet Code 35 Search Insert Position - 搜索插入位置-Java
- LintCode : 搜索二维矩阵
- lintcode-60-搜索插入位置
- 插入元素到有序数组,二分搜索查找插入位置
- lintcode 85 在二叉树中插入节点
- lintcode 173 单链表插入排序 python
- LintCode 插入区间
- 搜索插入位置
- lintcode: search for a range 搜索区间
- LintCode-61.搜索区间
- LintCode 30插入区间