LintCode 搜索区间
来源:互联网 发布:大数据时代杂志 编辑:程序博客网 时间:2024/06/06 08:44
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]和目标值target=8,
返回[3, 4]
挑战
时间复杂度 O(log n)
分别对左右边界进行二分查找。注意特殊情况的处理。直接看代码:
public class Solution { /* * @param A: an integer sorted array * @param target: an integer to be inserted * @return: a list of length 2, [index1, index2] */ public int[] searchRange(int[] A, int target) { // write your code here int[] res={-1,-1}; if(A.length==0){//数组为空,直接返回没找到 return res; } //查找右边界 int l=0,r=A.length-1; if(A[A.length-1]==target){//最后一个数等于target,直接设置 res[1]=A.length-1; } else{ while(l<=r){ int mid=l+(r-l)/2; if(A[mid]==target){ if(A[mid+1]==target){ l=mid+1; } else{ res[1]=mid; break; } } else if(A[mid]<target){ l=mid+1; } else{ r=mid-1; } } } if(res[1]==-1){//如果右边界没找到,那说明没有这个数,直接返回没找到 return res; } //查找左边界,右端起始位置直接设置为刚刚找到的右边界。 l=0;r=res[1]; if(A[0]==target){//第一个数等于target,直接设置 res[0]=0; } else{ while(l<=r){ int mid=l+(r-l)/2; if(A[mid]==target){ if(A[mid-1]==target){ r=mid-1; } else{ res[0]=mid; break; } } else if(A[mid]<target){ l=mid+1; } else{ r=mid-1; } } } return res; }}
阅读全文
0 0
- LintCode-搜索区间
- lintcode-搜索区间-61
- Lintcode搜索区间
- LintCode : 搜索区间
- LintCode:搜索区间
- LintCode 61-搜索区间
- LintCode : 搜索区间
- Lintcode 搜索区间
- lintcode(61)搜索区间
- LintCode 61 搜索区间
- [LintCode]61.搜索区间
- LintCode 搜索区间
- 搜索区间——LintCode
- LintCode——搜索区间
- LintCode-剑指Offer-(61)搜索区间
- [Lintcode]Search for a Range搜索区间
- Lintcode 二叉查找树中搜索区间
- lintcode-二叉查找树中搜索区间-11
- mac ntfs读写插件的双十一活动
- 14.(3)Struts2_值栈
- java多线程中Locks和ynchronized的区别
- [数学] Codechef September Challenge 2017 Weasel does Xor on Tree
- JS的内存泄漏
- LintCode 搜索区间
- leetcode 316. Remove Duplicate Letters(Hard)
- 面试常客,单例模式实现解析
- XCode的下载路径
- View的getWidth/getHeight与getMeasuredWidth/getMeasuredHeight的区别
- drawable+valuse+valuse-w820dp
- AnjularJs增查、排序
- hadoop 伪分布式安装
- C语言位运算符