Search for a Range
2014-02-26 09:29
260 查看
题目原型:
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
基本思路:
题目意思就是给定一个有序数组,然后给定一个目标数,在数组中查找目标数的起始范围,若没有找到则返回[-1,-1]。本题利用二分查找目标数,然后两边查找。
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,-1]。本题利用二分查找目标数,然后两边查找。
public int[] searchRange(int[] A, int target) { int[] result = new int[2]; int index; int start = 0; int end = 0; int temp1,temp2; index = search(A, 0, A.length-1, target); if(index==-1) { result[0]=-1; result[1]=-1; } else { temp1 = index-1; while(temp1>=0) { if(A[temp1]!=target) { start = temp1+1; break; } temp1--; } temp2 = index+1; while(temp2<A.length) { if(A[temp2]!=target) { end = temp2-1; break; } temp2++; } if(temp1<0) start=0; if(temp2>=A.length) end = A.length-1; result[0]=start; result[1]=end; } return result; } public int search(int[] A , int low , int high,int target) { if(low>high) return -1; int mid = (low+high)/2; if(target == A[mid]) return mid; else if(target>A[mid]) return search(A, mid+1, high, target); else return search(A, low, mid-1, target); }
相关文章推荐
- Ext.Net学习笔记17:Ext.Net GridPanel Selection
- android中的文件存储
- 星期三的一个上午
- SQL语句执行顺序及建议
- AFNetwork特性
- 程序员的人性思考(上)
- Ext.Net学习笔记16:Ext.Net GridPanel 折叠/展开行
- 软件开发模式对比(瀑布、迭代、螺旋、敏捷)
- C#文件与流(FileStream、StreamWriter 、StreamReader 、File、FileInfo、Directory、DirectoryInfo、Path、Encoding)
- MySQL必知必会之10-14
- Java Socket编程(模拟多用户聊天室)
- 如何更改linux文件的拥有者及用户组(chown和chgrp)
- pl/sql登不上,弹出空白对话框
- SNMP用VC实现的方法
- OpenGL: glew库
- Ext.Net学习笔记15:Ext.Net GridPanel 汇总(Summary)用法
- Oracle RAC系列之:利用srvctl管理RAC数据库
- ios--生命周期
- 2014正式开始我的技术之路
- Spring控制反转+依赖注入