LintCode : 搜索区间
来源:互联网 发布:淘宝怎么免费买东西 编辑:程序博客网 时间:2024/05/16 23:48
LintCode : 搜索区间
题目
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]和目标值target=8,
返回[3, 4]
思路
用二分法分别查找出目标值的左右边界。查找左边界时A[r]永远大于等于target,A[p]最后确定左边界。查找右边界是A[p]永远小于等于target, A[r]最后确定左边界。
代码
vector<int> searchRange(vector<int> &A, int target) { vector<int> result(2, -1); if(A.size() == 0) { return result; } int p = 0; int r = A.size() - 1; while(p < r) { int q = (p + r) / 2; if(A[q] < target) { p = q + 1; } else { r = q; } } if(A[p] == target) { result[0] = p; } p = 0; r = A.size()- 1; while(p < r) { int q = (p + r + 1) / 2; if(A[q] > target) { r = q - 1; } else { p = q; } } if(A[r] == target) { result[1] = r; } return result; }
0 0
- LintCode-搜索区间
- lintcode-搜索区间-61
- Lintcode搜索区间
- LintCode : 搜索区间
- LintCode:搜索区间
- LintCode 61-搜索区间
- LintCode : 搜索区间
- Lintcode 搜索区间
- lintcode(61)搜索区间
- LintCode 61 搜索区间
- [LintCode]61.搜索区间
- LintCode 搜索区间
- 搜索区间——LintCode
- LintCode——搜索区间
- LintCode-剑指Offer-(61)搜索区间
- [Lintcode]Search for a Range搜索区间
- Lintcode 二叉查找树中搜索区间
- lintcode-二叉查找树中搜索区间-11
- 并行光模块or普通光模块,哪一种更适合40G多模光纤布线
- 安卓介绍
- 人工智能(AI)第二节课总结
- HELLO WORLD
- Centos6.5下docker 环境搭建
- LintCode : 搜索区间
- Swift3.0带来的变化汇总系列一——字符串与基本运算符中的变化
- zookeeper设计原理
- Linux管道容量
- Spring AOP详解
- Maven导出Project依赖的jar包
- highcharts.js饼状图/折线图 二次开发
- CSS学习篇(1)_元素选择器
- 为什么我们的 Angular 应用总是很慢