LeetCode/二分法综合
作者:互联网
1. 寻找两个正序数组的中位数
2. 两数相除
3. 快速幂
4. 搜索旋转排序数组
5. 数组中的逆序对
6. 在排序数组中查找元素的第一个和最后一个位置
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
return {find(nums,target,true),find(nums,target,false)};
}
int find(vector<int>& nums, int target, bool minType) {
int left = 0, right = nums.size() - 1;
int ans = -1;//默认为-1
while (left <= right) {//当搜索区间位于两指针之间
int mid = left + (right - left) / 2;//二分查找
if (nums[mid] == target) {
ans = mid;
if (minType) right = mid - 1;//找左边界(注意没写反)
else left = mid + 1;}//找右边界(注意没写反)
else if (target < nums[mid]) right = mid - 1;//移动右指针到二分位置
else left = mid + 1;//左指针移到二分位置
}
return ans;
}
};
7. 找出第k小的数对距离
class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());//排序
int n = nums.size();
int left = 0, right = nums.back() - nums.front();
while (left <= right) {
int mid = (left + right) / 2;
int cnt = 0;//计算所有距离小于等于mid的数对数目cnt
for (int j = 0; j < n; j++) {
int i = lower_bound(nums.begin(), nums.begin() + j, nums[j] - mid) - nums.begin();
cnt += j - i;
}
if (cnt >= k) right = mid - 1;
else left = mid + 1;
}
return left;
}
};
8. 爱吃香蕉的珂珂
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
long sum =0;int max_ = 0;
for(int x:piles){
sum+=x;
max_ = max(max_,x);}
int min_ = ceil(sum*1.0/h);//向上取整
while(min_<max_){
int times = 0;
int mid = (max_+min_)/2;
for(int x:piles)
times = times + ceil(x*1.0/mid);
if(times==h) max_ = mid; //找左边界动右边
else if(times<h) max_ = mid;
else if(times>h) min_ = mid+1;//找左边界
}
return min_;
}
};
标签:nums,int,max,min,二分法,vector,LeetCode,综合,left 来源: https://www.cnblogs.com/929code/p/16535801.html