34. Search for a Range
2016-03-21 11:22
429 查看
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
Subscribe to see which companies asked this question
先找前面的 再找后面的 没难度
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].
Subscribe to see which companies asked this question
先找前面的 再找后面的 没难度
public class Solution { public int[] searchRange(int[] nums, int target) { if(nums.length==1&&nums[0]==target){ int [] re ={0,0}; return re; } if(nums.length==1&&nums[0]!=target){ int [] re ={-1,-1}; return re; } int a = 0; int c = nums.length-1; int b = (a+c)/2; int first = -1; int last = -1; while(c-a>=10){//先找前面的 if(nums[b]>=target){//前面的落在前半截 c=b; b=(a+c)/2; continue; }else{ a=b; b=(a+c)/2; continue; } } if(nums[0]==target){first=0;}else{ for(int i=a;i<=c;i++){ if(nums[i]==target&&nums[i-1]<target){first=i;break;} } } a=0;c=nums.length-1;b=(a+c)/2; while(c-a>=10){//再找后面的 if(nums[b]<=target){// a=b; b=(a+c)/2; continue; }else{ c=b; b=(a+c)/2; continue; } } if(nums[nums.length-1]==target){last=nums.length-1;}else{ for(int i=c;i>=a;i--){ if(nums[i]==target&&nums[i+1]>target){last=i;break;} }} int [] res = {first,last}; 4000 return res; } }
相关文章推荐
- 怎么快速修改iMindMap浮动文本格式
- Fragment AutoCompleteTextView xml动画(补间 属性动画)
- 写代码专用开头
- java提高篇-----详解java的四舍五入与保留位
- db2远程链接方法
- java api文档的阅读技巧
- java调用ffmpeg获取视频时长
- 如何在自己的网页中加入天气预报
- 【转】spring 装配Bean中构造参数的注入
- NSURLSessionDataTask
- 学习笔记之代码大全2
- Linux Redis安装
- Maven编译问题,Connection TimeOut
- 147. Insertion Sort List
- Daum Equation Editor(公式编辑器)
- python中if __name__ == '__main__': 的解析
- 异常的补充
- 怎样快速搜索自己所需的资料?(90%的人不会使用此方法)
- 跨平台开发与原生开发优劣比较
- windows下修改memcached服务的端口号