Search for a Range
2015-11-10 12:00
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
public class Solution {
public int[] searchRange(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = (start + end)/2;
if(nums[mid] > target){
end = mid - 1;
continue;
}
else if (nums[mid] < target){
start = mid + 1;
continue;
}
else {
int[] result = new int[2];
int i = mid;
while(i >= 0 && nums[i] == nums[mid]){
i--;
}
result[0] = i + 1;
i = mid;
while(i < nums.length && nums[i] == nums[mid]){
i++;
}
result[1] = i - 1;
return result;
}
}
return new int[] {-1, -1};
}
}
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) {
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = (start + end)/2;
if(nums[mid] > target){
end = mid - 1;
continue;
}
else if (nums[mid] < target){
start = mid + 1;
continue;
}
else {
int[] result = new int[2];
int i = mid;
while(i >= 0 && nums[i] == nums[mid]){
i--;
}
result[0] = i + 1;
i = mid;
while(i < nums.length && nums[i] == nums[mid]){
i++;
}
result[1] = i - 1;
return result;
}
}
return new int[] {-1, -1};
}
}
相关文章推荐
- CLion中配置OpenCV环境问题
- 小技巧5-iOS 统计Xcode整个工程的代码行数
- remount of system failed: Permission denied
- gridview单元格长度设置
- 正确的健身走方法
- Linux文本处理三剑客之awk
- 使用 ConfigSource 特性 拆分 Web.config 文件
- 关于JQUERY的AJAX跨域问题
- 抻筋拔骨操:健身走4
- MD(d)、MT(d)编译选项的区别
- Flume之ChannelProcessor源码分析
- 快速排序
- SQL Server创建数据库和数据表的相关约束实现方法
- solr+zookeeper注意事项
- 常用正则表达式大全,手机、电话、邮箱、身份证(最严格的验证)、IP地址、网址、日期等,一般前台js验证
- android studio 启动android device monitor 报java虚拟机启动失败
- c语言学习之基础知识点介绍(二十):预处理指令
- 连接oracle服务器超慢--原因分析
- Linux中安装sosreport和supportconfig来收集系统信息
- javax.el.PropertyNotFoundException: Property 'eyeSuggest' not readable on type org.smt.entity.Health