题目描述:
代码:
class Solution {
public int search(int[] nums, int target) {
int len = nums.length;
int l = 0;
int r = len - 1;
int mid = 0;
int coutr,coutl = 0;
if(len == 0)
return 0;
while(l<=r){
mid = l + (r - l)/2;
if(nums[mid] > target){//相等时r=mid-1,区间向右缩
r =mid - 1;
}
else l = mid + 1;;
}
if(r>=0 && nums[r]==target)
coutr = r;
else
return 0;
l = 0;
r = len - 1;
while(l<=r){
mid= l + (r - l)/2;
if(nums[mid] >= target){//相等时r=mid-1,区间向左缩
r = mid - 1;
}
else l = mid + 1;
}
if(l<len&&nums[l]==target)
coutl = l;
else
return 0;
return coutr - coutl + 1;
}
}
题解:
暴力解法不再赘述。思路就是二分查找,但是写的时候有太多细节没有掌握
- mid = l + (r - l)/2 因为l+r可能会溢出
- mid-1与mid+1这个问题困扰了很久,在知乎一篇帖子中看到了别人的分析后豁然开朗。这就是一个闭合区间的问题
r=mid-1
意思是[nums[l],nums[mid])
,l=m+1
意思是(nums[mid],nums[r]]
。帖子链接https://www.zhihu.com/question/36132386/answer/712269942