题目:
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:
1.Numbers of houses and heaters you are given are non-negative and will not exceed25000
.
2.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.
Example 2:
Input: [1,2,3,4],[1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
解释:
解法1:
step1:
找出每个house距离它最近的heater的距离
step2:
找到所有距离中的最大值 O(n2)TLE,呵呵
解法2:
分析:先将所有的房子和加热器按照先后顺序排好,因为如果一个房子已经确定了离他最近的加热器,那么他后面的房子离其最近的加热器肯定在当前这个加热器后面(或者这个加热器)的位置,而且当tmp开始比当前比较的距离小了以后,就无需再比较了,因为后面的距离只能更大,直接break
就好,事实上是对解法1的优化,避免了无意义的比较。
解法1,超时,python代码:
import sys
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
result=0
houses.sort()
heaters.sort()
for i in xrange(len(houses)):
temp=sys.maxint
for j in xrange(len(heaters)):
_abs=abs(houses[i]-heaters[j])
if temp>_abs:
temp=_abs
else:
break
result=max(result,temp)
return result
解法2:
python代码
import sys
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
result=0
houses.sort()
heaters.sort()
if houses==heaters:
return 0
jdx=0
for i in xrange(len(houses)):
temp=float('inf')
for j in xrange(jdx,len(heaters)):
_abs=abs(houses[i]-heaters[j])
if temp>_abs:
temp=_abs
jdx=j
else:
break
result=max(result,temp)
return result
c++代码:
#include <cmath>
using namespace std;
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(heaters.begin(),heaters.end());
sort(houses.begin(),houses.end());
if(houses==heaters)
return 0;
int n=houses.size();
int m=heaters.size();
int jidx=0;
int result=INT_MIN;
for(int i =0;i<n;i++)
{
int tmp=INT_MAX;
for (int j=jidx;j<m;j++)
{
int _abs=abs(houses[i]-heaters[j]);
if (tmp>=_abs)
{
jidx=j;
tmp=_abs;
}
else
break;
}
result =max(result,tmp);
}
return result;
}
};
总结:
注意,如果排好序的两个数组相等,直接返回0即可,可以节省大量时间。