[LintCode]61.搜索区间
来源:互联网 发布:mac上flash player 编辑:程序博客网 时间:2024/06/06 08:58
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]
和目标值target=8
,
返回[3, 4]
思路:二分查找
class Solution {public: /* * @param A: an integer sorted array * @param target: an integer to be inserted * @return: a list of length 2, [index1, index2] */ vector<int> searchRange(vector<int> A, int target) { vector<int> result; int size = A.size()-1; if(A.empty()) { result.push_back(-1); result.push_back(-1); } else { result.push_back(getFirstTarget(A, target, 0, size)); result.push_back(getLastTarget(A, target, 0, size)); } return result; } //找左边界 int getFirstTarget(vector<int> &A, int target, int low, int high){ if(low > high) return -1; int mid = (low+high)/2; if(A[mid] == target) { if((mid>0 && A[mid-1]!=target) || mid==0) return mid; else high = mid-1; } else if(A[mid] > target) high = mid-1; else low = mid+1; return getFirstTarget(A, target, low, high); } //找右边界 int getLastTarget(vector<int> &A, int target, int low, int high){ int size = A.size()-1; if(low > high) return -1; int mid = (low+high)/2; if(A[mid] == target) { if((mid<size && A[mid+1]!=target) || mid==size) return mid; else low = mid+1; } else if(A[mid] > target) high = mid-1; else low = mid+1; return getLastTarget(A, target, low, high); }};
阅读全文
0 0
- [LintCode]61.搜索区间
- LintCode-搜索区间
- lintcode-搜索区间-61
- Lintcode搜索区间
- LintCode : 搜索区间
- LintCode:搜索区间
- LintCode 61-搜索区间
- LintCode : 搜索区间
- Lintcode 搜索区间
- lintcode(61)搜索区间
- LintCode 61 搜索区间
- LintCode 搜索区间
- 搜索区间——LintCode
- LintCode——搜索区间
- LintCode-剑指Offer-(61)搜索区间
- [Lintcode]Search for a Range搜索区间
- Lintcode 二叉查找树中搜索区间
- lintcode-二叉查找树中搜索区间-11
- 141. Linked List Cycle
- Android客户端与服务器通信的架构图及代码参考
- 单击事件分发机制-源码分析
- ZOJ 1117 Entropy(哈夫曼树)
- static静态局部变量
- [LintCode]61.搜索区间
- hdu 1181
- 分页查询pageHelper
- 分布式存储系统 知识体系
- 模板语言基本说明
- Linux下mongodb(一):安装与使用
- 安装MyEclipse2017 出现 network setup 问题,解决办法
- Xcode消除警告
- 进程间通信之共享内存技术