利用二分思想先找其左边界,再找其右边界即可,注意找左边界的时候,由右侧逼近;找右边界的时候,由左侧逼近,即可。
向下取整求左边界
+1向上取整求右边界
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left=0;
int right=nums.size()-1;
if(nums.empty()) return {-1,-1};
while(left<right)
{
int mid=left+((right-left)>>1);
if(nums[mid]>=target)
{
right=mid;
}
else left=mid+1;
}
if(nums[left] != target) return {-1,-1};
int start=left;
left=0;
right=nums.size()-1;
while(left<right)
{
int mid=left+((right-left+1)>>1);
if(nums[mid]<=target)
{
left=mid;
}else right=mid-1;
}
if(nums[left] != target) return {-1,-1};
int end=right;
return {start,end};
}
};
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int num=0;
for (auto x:grid){
int l=0,r=(int)x.size()-1,pos=-1;
while (l<=r){
int mid=l+((r-l)>>1);
if (x[mid]<0){
pos=mid;
r=mid-1;
}
else l=mid+1;
}
if (pos!=-1) num+=(int)x.size()-pos;// pos=-1表示这一行全是>=0的数,不能统计
}
return num;
}
};