LeetCode 1620.网络信号最好的坐标
思路
模拟题
根据题目要求,如果有多个网络信号最好的坐标,则返回网络信号最好的非负坐标,此时 cx>=0且cy>=0。
因此结果坐标满足大于0小于x/yMax的条件,所以只需在此范围内遍历每一个可能的坐标,计算其信号强度之和,即可找到符合信号最好的坐标。
代码
class Solution {
public:
int getSquaredDistance(const vector<int> coordinate, const vector<int> tower)
{
return pow(tower[0]- coordinate[0], 2) + pow(tower[1] - coordinate[1], 2);
}
vector<int> bestCoordinate(vector<vector<int>>& towers, int radius) {
int xMax=INT_MIN, yMax=INT_MIN;
for(auto &&tower:towers)
{
int x=tower[0], y=tower[1];
xMax=max(x, xMax);
yMax=max(y, yMax);
}
int cx=0, cy=0;
int maxQuality=0;
for(int x=0;x<=xMax;x++)
{
for(int y=0;y<=yMax;y++)
{
vector<int> coordinate={x, y};
int quailty=0;
for(auto &&tower:towers)
{
int squaredDistance = getSquaredDistance(coordinate, tower);
if(squaredDistance<=radius * radius)
{
double distance = sqrt((double)squaredDistance);
quailty += floor((double)tower[2] / (1+distance));
}
}
if(quailty>maxQuality)
{
cx = x;
cy = y;
maxQuality = quailty;
}
}
}
return {cx, cy};
}
};