Search for a Range
2016-05-07 18:36
211 查看
题目描述:
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].
这里用了二分法的思想。
如果value比数组的最大值大,比最小值小,那么就直接返回[-1, -1]。
如果数组都是同一个数且等于value,就直接返回[0,n-1]。(n为数组长度)
如果数组的最左边等于value,则从左往右寻找有多少个等于value的值
如果数组的最右边等于value,则从右往左寻找有多少个等于value的值
否则就看nums[mid],其中mid=(left+right)/2。如果nums[mid]等于value,就从中间向两边寻找等于value的值,如果nums[mid]小于value,那么value肯定在数组的右边,如果nums[mid]大于value,那么value肯定在数组的左边。
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].
这里用了二分法的思想。
如果value比数组的最大值大,比最小值小,那么就直接返回[-1, -1]。
如果数组都是同一个数且等于value,就直接返回[0,n-1]。(n为数组长度)
如果数组的最左边等于value,则从左往右寻找有多少个等于value的值
如果数组的最右边等于value,则从右往左寻找有多少个等于value的值
否则就看nums[mid],其中mid=(left+right)/2。如果nums[mid]等于value,就从中间向两边寻找等于value的值,如果nums[mid]小于value,那么value肯定在数组的右边,如果nums[mid]大于value,那么value肯定在数组的左边。
public class Solution { public int[] searchRange(int[] nums, int target) { int n=nums.length; int[] a=new int[]{-1,-1}; if(n==0) return a; int[] result=search(nums, 0, n-1, target); return result; } public int[] search(int[] nums,int left,int right,int target){ int[] a=new int[]{-1,-1}; if(target>nums[right]||target<nums[left]){ }else if(nums[left]==nums[right]){ a[0]=left;a[1]=right; }else if(nums[left]==target&&nums[right]!=target){ int index=left+1; while(nums[index]==target){ index++; } a[0]=left;a[1]=index-1; }else if(nums[right]==target&&nums[left]!=target){ int index=right-1; while(nums[index]==target){ index--; } a[0]=index+1;a[1]=right; }else{ int mid=(left+right)/2; if(nums[mid]==target){ int i=mid-1; int j=mid+1; while(nums[i]==target){ i--; } while(nums[j]==target){ j++; } a[0]=i+1;a[1]=j-1; }else if(nums[mid]<target){ return search(nums, mid+1, right, target); //这里不能是(nums, mid, right, target) }else if(nums[mid]>target){ return search(nums, left, mid, target); } } return a; } }
相关文章推荐
- 蛇形填数
- matlab中cell的用法
- 探索博客园的“打赏”模式
- hdu 4612 求边连通分量+求树的直径
- 平行四边形数
- springcloud(第四篇)springcloud hystrix
- shell自动监控重启Tomcat脚本
- Yii表单的使用
- github desktop 在线安装失败解决方案
- Android清理内存
- hdoj2050代码及详解
- xampp 设置虚拟主机
- MVC4的缓存
- Codeforces 635D Factory Repairs (树状数组)
- RMAN实战
- Codeforces Round #350 (Div. 2)
- 《STL源码剖析》学习笔记-第5章 关联式容器
- Linux basic knowledge
- Activity和Service之间只相差了一个Window
- python logging 日志轮转文件不删除问题