Search for a Range
2015-07-22 10:37
399 查看
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].
题目要求了时间复杂度,因此需要用二分搜索。
在num[i]==target时处理完毕应该返回arr,否则会死循环。写代码为这个问题纠结很久。
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].
题目要求了时间复杂度,因此需要用二分搜索。
在num[i]==target时处理完毕应该返回arr,否则会死循环。写代码为这个问题纠结很久。
public class Solution { public int[] searchRange(int[] nums, int target) { int[] arr={-1,-1}; int left=0,right=nums.length-1; if(right<left) return arr; while(left<=right){ int mid=left+(right-left)/2; if(nums[mid]==target){ while(nums[left]<target)left++; while(nums[right]>target)right--; arr[0]=left;arr[1]=right; return arr; } else if(nums[mid]<target) left=mid+1; else right=mid-1; } return arr; } }
相关文章推荐
- Hduoj2830 【矩阵数学】
- hdoj 3367 Pseudoforest 【伪森林】 【并查集判断环 + 最大生成树】
- Spring笔记
- Linux 命令——tee 重定向到文件并打印到屏幕
- PeopleCode 代码收集
- oracle索引方式详解
- 【Java】两个排序后的数组A和B,其中A的末端有足够的缓冲容纳B。编写一个方法,将B合并入A并排序。
- Java4Android-继承初步
- Android APK签名对比及说明
- mongodb 3.0 创建用户 开启认证
- 数组与指针
- Swap 2 Variables in Python
- String类和StringBuffer类
- myEclipse2015启动myEclipse时发现了以元素"d:disk"的无效内容
- 插入代码测试
- 图文混排
- linux grep命令
- 1.从第一道面试题谈起
- 使用Fragment的原因
- atoi和itoa(头文件stdilb.h)的C实现