首页 > 代码库 > Search for a Range
Search for a Range
这道题没什么好说的,二分法查找
class Solution {public: vector<int> range; vector<int> searchRange(int A[], int n, int target) { range.push_back(-1); range.push_back(-1); if(n == 0) return range; int max,min,middle; max = n-1; min =0; middle = (max + min)/2; while(min <= max) { if(A[middle] > target) { max = middle -1; middle = (min + max)/2; } else if(A[middle] < target) { min = middle + 1; middle = (min + max)/2; } else { break; } } if(A[middle] != target) return range; min = middle; while(1) { if(min - 1 >=0) { if(A[min-1] != target) { break; } min = min-1; } else { break; } } max = middle; while(1) { if(max + 1 <n) { if(A[max + 1 ] != target) { break; } max = max + 1; } else { break; } } range.clear(); range.push_back(min); range.push_back(max); return range; } };
Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。