[leedcode 34] Search for a Range
2015-07-09 18:09
323 查看
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
For example,
Given
return
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].
public class Solution { public int[] searchRange(int[] nums, int target) { //本题是在已排序的数组中进行查找,因此应用二分查找的思想 //牢记二分查找的参数以及函数! //当找到target数时,进行顺序查找,设置两个指针,一个是left,代表最侧不为target的下标。另一个是right,代表最右侧不为target的下标 //注意int 数组的初始化!int a[]={-1,-1}; int[] result={-1,-1}; if(nums.length<1) return result; int res=find(nums,target,0,nums.length-1); if(res==-1){ return result; } int left=res-1; int right=res+1; while(left>=0&&nums[left]==target){ left--; } while(right<nums.length&&nums[right]==target){ right++; } int rel[]={left+1,right-1}; return rel; } public int find(int[] nums,int target,int start,int end){ if(start>end) return -1; int mid=(start+end)/2; if(nums[mid]==target){ return mid; } if(target>nums[mid]){ return find(nums,target,mid+1,end); }else{ return find(nums,target,start,mid-1); } } }
相关文章推荐
- 百度定位sdk Couldn't load locSDK4 from loader dalvik
- 大素数高效算法判断
- 美国硅谷
- 寻找失踪的整数数组(Find the missing integer)
- Android:关于声明文件中android:process属性说明
- 树的定义及术语
- iOS property 用法
- 加载并获取jar包中某个类的某个方法
- 霍夫曼编码/译码器
- 第八章 面向对象之一:对象的理解
- Python+django开发环境搭建
- C#建立最简单的web服务,无需IIS
- BCP 简 要 说 明
- Java - Thinking in Java 第3章 操作符
- Linux 下如何处理包含空格和特殊字符的文件名
- Oracle创建存储过程、创建函数、创建包
- 手斧Linux – 从LFS到Funtoo (155)
- NGUI奇葩的collider不能触发的问题处理
- 问题解决 —— Jsp界面之间传参乱码
- Linux 下如何处理包含空格和特殊字符的文件名