34. Search for a Range (Array; Divide-and-Conquer)
2015-10-03 11:46
591 查看
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
思路:先二分法找最左端,再二分法找最右端。保证稳定排序。具体实现:
相同元素返回最左元素:start总是在<target位置,所以从-1开始
相同元素返回最右元素:end总是在>target位置,所以从n开始
二者的结束条件都是start+1==end
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].
思路:先二分法找最左端,再二分法找最右端。保证稳定排序。具体实现:
相同元素返回最左元素:start总是在<target位置,所以从-1开始
相同元素返回最右元素:end总是在>target位置,所以从n开始
二者的结束条件都是start+1==end
class Solution { public: vector< int > searchRange(int A[], int n, int target) { result.clear(); binarySearchLeft(A,-1,n,target); if(result[0]!=-1) binarySearchRight(A,-1,n,target); return result; } void binarySearchLeft(int A[], int start, int end, int target){ //find the first value == target if (start+1 == end){ if(end >= n || A[end]!=target){ result.push_back(-1); result.push_back(-1); } else result.push_back(end); return; } int mid = start + ((end-start)>>1); if (A[mid] < target) binarySearchLeft(A, mid, end, target); else binarySearchLeft(A, start, mid, target); } void binarySearchRight(int A[], int start, int end, int target){ //find the first value == target if (start+1 == end){ result.push_back(start); return; } int mid = start + ((end-start)>>1); if (A[mid] > target) binarySearchRight(A, start, mid, target); else binarySearchRight(A, mid, end, target); } private: vector< int > result; };
相关文章推荐
- 关于[UIColor clearColor] 与控件的属性:alpha
- Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
- ZOJ 3349 Special Subsequence
- UVa694 - The Collatz Sequence:Time limit exceeded
- qemu guest agent安装研究
- OC学习笔记之Foundation框架NSNumber、NSValue和NSDate(转)
- Repeated DNA Sequences
- HDU 1159 & POJ 1458 Common Subsequence(LCS 最长公共子序列O(nlogn))
- ucGUI学习笔记之对话框
- 128. Longest Consecutive Sequence (List, Queue)
- iOS的实时搜索:UISearchBar与UISearchController
- UI:修改模拟器类型、多线程理解
- UVALive 6432 Influence // 暴力dfs
- ZOJ 3820 Building Fire Stations
- Debian Stable (Jessie 8.1) 的normal.mod not found
- hdu 5493 Queue(线段树)
- unique_ptr
- 多个线程操作StringBuffer和StringBuilder
- 用g++ 编译 ffmpeg 编译出现 error: 'UINT64_C' was not declared in this scope 或 missing -D__STDC_CONSTANT_MACROS
- codeforces 466D Increase Sequence DP