Heaters
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
Note:
- Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
- Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
- As long as a house is in the heaters' warm radius range, it can be warmed.
- All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
1. 先将heaters进行sort,然后二分查找每个house最近的heater
2. 也可以把两个都排序,然后查找的左边界可以不断的缩小。但是这样做的耗时很高,应该是和具体的用例有关
2. 这个解法最后要500多ms,但是discuss上好多答案都是超时的。。奇怪
int binarySearch(vector<int>& heaters, int target){
int left = 0;
int n = heaters.size();
int right = n - 1;
while (left <= right){
int half = left + (right - left) / 2;
if(heaters[half] == target) return 0;
else if(heaters[half] < target) left = half + 1;
else right = half - 1;
}
if (right < 0) return heaters[0] - target;
if (left > n - 1) return target - heaters[n-1];
return min(target-heaters[right], heaters[left]-target);
}
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(heaters.begin(), heaters.end());
int maxDis = 0;
int left = 0;
for(int h : houses){
maxDis = max(maxDis, binarySearch(heaters, h));
left = max(left-1, 0);
}
return maxDis;
}
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt
.
Example 1:
Input: 16 Returns: True
bool isPerfectSquare(int num) {
long left = 1;
long right = num;
while (left <= right){ //要有等号
long half = (left + right) / 2;
if (half * half == num) return true;
else if (half * half > num) right = half - 1;
else left = half + 1;
}
return false;
}