61. 搜索区间
来源:互联网 发布:js怎么判断日期相等 编辑:程序博客网 时间:2024/06/14 22:52
题目描述
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]和目标值target=8,
返回[3, 4]
思路
直接用两次二分搜索,第一次寻找target出现的第一个位置,第二次寻找target出现的最后一个位置,时间复杂度为O(2logn)。如果直接搜索到一个target值在从该位置前后顺序搜索,最坏情况下耗时为O(nlogn),比如数组为{5,5,5,5,5,5.。。。。}
代码
public class Main { /* * @param A: an integer sorted array * @param target: an integer to be inserted * @return: a list of length 2, [index1, index2] */ public static int[] searchRange(int[] A, int target) { // write your code here if (A.length == 0) { return new int[]{-1, -1}; } int start, end, mid; int[] bound = new int[2]; // search for left bound start = 0; end = A.length - 1; while (start +1 < end) { mid = start + (end - start) / 2; if (A[mid] == target) { end = mid; } else if (A[mid] < target) { start = mid; } else { end = mid; } } if (A[start] == target) { bound[0] = start; } else if (A[end] == target) { bound[0] = end; } else { bound[0] = bound[1] = -1; return bound; } // search for right bound start = 0; end = A.length - 1; while (start +1 < end) { mid = start + (end - start) / 2; if (A[mid] == target) { start = mid; } else if (A[mid] < target) { start = mid; } else { end = mid; } } if (A[end] == target) { bound[1] = end; } else if (A[start] == target) { bound[1] = start; } else { bound[0] = bound[1] = -1; return bound; } return bound; }}
阅读全文
0 0
- [LintCode]61.搜索区间
- 61. 搜索区间
- 搜索区间
- 搜索区间
- LintCode-搜索区间
- 区间搜索(算法)
- lintcode-搜索区间-61
- Lintcode搜索区间
- LintCode : 搜索区间
- LintCode:搜索区间
- 面试:数组:区间搜索
- yii在区间搜索
- yii区间搜索
- yii区间搜索
- LintCode 61-搜索区间
- LintCode : 搜索区间
- Lintcode 搜索区间
- lintcode(61)搜索区间
- Web Api 2.0中使用Swagger生成Api文档的2个小Tips
- ArrayList的实现原理
- 为DedeCMS系统自定义字段的图片去掉宽高
- mysql 常用命令总结
- 比特率 波特率 数据传输速率 区别
- 61. 搜索区间
- 使用Matplotlib文本注解绘制树节点
- 判断是否是微信端的代码
- 你不知道的h5
- python map函数处理字典
- 1059. C语言竞赛(20) PAT乙级真题
- webpack和gulp结合使用
- oracle 根据某个字段分组,再根据另一个字段排序的sql查询 即 组内排序
- Mac安装CAJViewer