leetcode-二分
作者:
呜呜呜
,
2021-03-30 17:11:58
,
所有人可见
,
阅读 384
69. x 的平方根
class Solution {
public:
int mySqrt(int x) {
int l=0,r=x;
while(l<r)
{
int mid=(1ll+l+r)>>1;
if(1ll*mid*mid<=x)l=mid;
else r=mid-1;
}
return l;
}
};
35. 搜索插入位置
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l=0,r=nums.size();
while(l<r)
{
int mid=(r+l)>>1;
if(nums[mid]>=target)r=mid;
else l=mid+1;
}
return l;
}
};
1760. 袋子里最少数目的球
class Solution {
public:
bool check(vector<int>&nums,int x,int maxOperations)
{
int cnt=0;
int n=nums.size();
for(int i=0;i<n;i++)
{
cnt+=(nums[i]-1)/x;
}
return cnt<=maxOperations;
}
int minimumSize(vector<int>& nums, int maxOperations) {
int l=1,r=1e9;
while(l<r)
{
int mid=l+r>>1;
if(check(nums,mid,maxOperations))r=mid;
else l=mid+1;
}
return l;
}
};