Lintcode 搜索区间
来源:互联网 发布:亚麻籽粉 知乎 编辑:程序博客网 时间:2024/06/06 08:56
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]
和目标值target=8
,
返回[3, 4]
挑战
时间复杂度 O(log n)
标签
class Solution { /** *@param A : an integer sorted array *@param target : an integer to be inserted *return : a list of length 2, [index1, index2] */public: vector<int> searchRange(vector<int> &A, int target) { // write your code here vector<int> result; result.push_back(-1); result.push_back(-1); if(A.empty()) return result; int n=A.size(); int begin=0,end=n-1,mid; while(begin<end){ mid=(begin+end)/2; if(A[mid]==target){ begin=mid; break; } else if(A[mid]<target) begin=mid+1; else end=mid-1; } int i,j; if(A[begin]==target){ i=begin; j=begin; while(A[i]==target) i--; while(A[j]==target) j++; result[0]=i+1; result[1]=j-1; } return result; }};
如有问题请留言。
转载请注明出处。
1 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
- Linux权限与用户
- SQL返回表
- logistic回归原理解析及Python应用实例
- Android通过ContentProvider获取通话记录
- MFC基础知识
- Lintcode 搜索区间
- HTML编程快速入门教程
- Unity3D学习——井字棋游戏
- LeetCode66. Plus One
- linux运维-系统服务的控制
- 家装类网站建设如何定位和优化运营
- 练习
- 基于node.js的简单本地服务器搭建
- 剑指offer:二叉搜索树与双向链表