[LeetCode] Search for a Range
2013-11-07 09:06
337 查看
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log
n).
If the target is not found in the array, return
For example,
Given
return
问题描述:给定一个排序的整数数组,找到一个给定值的起始和终止位置,算法的时间复杂度是O(log n)。
由于算法的时间复杂度是O(log n),因此,可以采用二分查找,只不过当查找到给定的值时,要向左和向右进行延伸,看是否有重复的元素。
Your algorithm's runtime complexity must be in the order of O(log
n).
If the target is not found in the array, return
[-1, -1].
For example,
Given
[5, 7, 7, 8, 8, 10]and target value 8,
return
[3, 4].
问题描述:给定一个排序的整数数组,找到一个给定值的起始和终止位置,算法的时间复杂度是O(log n)。
由于算法的时间复杂度是O(log n),因此,可以采用二分查找,只不过当查找到给定的值时,要向左和向右进行延伸,看是否有重复的元素。
class Solution { public: vector<int> searchRange(int A[], int n, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int left = 0, right = n - 1, mid = 0; vector<int> vec; while(left <= right) { mid = (left + right) / 2; if(target > A[mid]) left = mid + 1; else if(target < A[mid]) right = mid - 1; else { int i = mid; while(i >= left && A[i] == target) --i; int j = mid; while(j <= right && A[j] == target) ++j; vec.push_back(++i); vec.push_back(--j); return vec; } } vec.push_back(-1); vec.push_back(-1); return vec; } };
相关文章推荐
- Javascript SHA-1:Secure Hash Algorithm
- [转]可视化的数据结构和算法
- 统计文件中不小于某一长度的单词的个数(泛型算法实现)
- 使用他人的MD5编码类,修改形成密码串
- Extracting Structured Data from Web Pages
- (译)Cocos2d_for_iPhone_1_Game_Development_Cookbook:1.13使用CCTexture2DMutable调换调色盘
- Java中3DES加密
- Refactoring Notes-Refactoring Methods(3)
- 图书馆管理程序~~不过貌似功能!!有空再修修
- trainging contest#2(2011成都现场赛)I BY Hyoga
- C/C++头文件包含内容概览
- 堆栈的应用(1) 平衡符号 C++实现
- 程序员编程艺术第一章、左旋转字符串
- 程序员编程艺术:第三章续、Top K算法问题的实现
- 程序员编程艺术:第四章、现场编写类似strstr/strcpy/strpbrk的函数
- 十四、第三章再续:快速选择SELECT算法的深入分析与实现
- 程序员编程艺术:第七章、求连续子数组的最大和
- 程序员编程艺术:第八章、从头至尾漫谈虚函数
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第十章、如何给10^7个数据量的磁盘文件排序