供暖器
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
//先将供暖器排序,之后为每个屋子找到最近的供暖器
heaters.push_back(INT_MIN),heaters.push_back(INT_MAX);
sort(heaters.begin(),heaters.end());
int res = 0;
for(int i=0;i<houses.size();i++){
int l=0,r = heaters.size()-1;
while(l-r){
int mid = l+r>>1;
if(heaters[mid]>houses[i]) r = mid;
else l = mid+1;
}
res = max(res,(int)min(heaters[l]-0ll-houses[i],houses[i]-0ll-heaters[l-1]));
}
return res;
}
};
寻找峰值
//如果左边的比右边的值要小的话,那么在右边就会必有一个值是峰值
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if(nums.size()==1||nums[0]>nums[1]) return 0;
int l = 1,r = nums.size()-1;
while(l-r){
int mid = l+r+1>>1;
if(nums[mid]>nums[mid-1]) l = mid;
else r = mid-1;
}
return l;
}
};