leetcode_Search for a Range
来源:互联网 发布:彩票源码系统php 编辑:程序博客网 时间:2024/06/06 16:32
描述:
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 [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
思路:
1.二分查找,找到value为target的一个元素的位置,找不到返回[-1,-1]
2.假设找到位置,且为index,分别向两边拓展即可。
代码:
public int[] searchRange(int[] A, int target) { int arr[]=new int[2]; Arrays.fill(arr, -1); if(A==null||A.length==0) return arr; int len=A.length; int start=0,end=len-1; int mid=0; int index=-1; while(start<=end) { mid=(start+end)/2; if(A[mid]==target) { index=mid; break; }else if(A[mid]<target) start=mid+1; else end=mid-1; } if(index==-1) return arr; int i=1,temp=index-i; while(temp>=0&&A[temp]==target) { i++; temp=index-i; } arr[0]=index-i+1; i=1; temp=index+i; while(temp<len&&A[temp]==target) { i++; temp=index+i; } arr[1]=index+i-1; return arr; }
0 0
- Leetcode_search-for-a-range
- leetcode_Search for a Range
- Leetcode_Search for a Range
- leetCode_Search for a Range(二分查找)
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range !!!
- Search for a Range
- Search for a Range
- Search For A Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- 算法导论 改进快排(3)---栈深度 习题7-4
- Android 动画AlphaAnimation类方法
- 【连载】 .Net cad二次开发(一)
- nyoj 813 对决
- SQL Server 2008 数据库引擎等安装失败的原因
- leetcode_Search for a Range
- Device Tree(三):代码分析
- 黑马程序员_Java基础_网络编程
- JNI/NDK开发指南(十一)——JNI异常处理
- Java移位运算符
- 老公老婆开玩笑。。。哈哈,笑死你
- 汉诺塔VI
- Linux--进程组、会话、守护进程
- SB tree——A temporal aggregation data structure