二刷34.|二刷34. Search for a Range
【二刷34.|二刷34. Search for a Range】出 bug的地方:
- 一开始没判断nums == null || nums.length == 0
- 二分搜索的时候有可能start就没找到,这个时候start=first会导致start = -1后面你用nums[start]就会数组越界. 所以搜索完start的时候你要记得判断一下start == -1?如果等于说明nums里面没有target你要直接返回[-1,-1]
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0){
return new int[]{-1,-1};
}
//[1]
//0
int first = -1;
int last = -1;
int start = 0;
int end = nums.length - 1;
while (start + 1 < end){
int mid = start + (end - start) / 2;
if (nums[mid] >= target){
end = mid;
} else {
start = mid;
}
}
if (nums[start] == target){
first = start;
} else if (nums[end] == target){
first = end;
}
start = first;
end = nums.length - 1;
if (start == -1){
return new int[]{-1,-1};
}
while (start + 1 < end){
int mid = start + (end - start) / 2;
if (nums[mid] <= target){
start = mid;
} else {
end = mid;
}
}
if (nums[end] == target){
last = end;
} else if (nums[start] == target){
last = start;
}
return new int[]{first, last};
}
}
推荐阅读
- 前沿论文|论文精读(Neural Architecture Search without Training)
- ElasticSearch6.6.0强大的JAVA|ElasticSearch6.6.0强大的JAVA API详解
- Elasticsearch|Elasticsearch 简介
- 扫黑-决战-一部让我看完后立刻想二刷的电影
- elasticsearch分析器
- 三十一、|三十一、 Elasticsearch集群搭建部署及配置
- oh|oh my love
- springmvc|springmvc 集成 Spring Data Elasticsearch 遇到的坑
- Elasticsearch(一)什么是Elasticsearch
- elasticsearch|elasticsearch 7.0 新特性之 search as you type