LeetCode·每日一题·1620.网络信号最好的坐标·模拟
2023-09-27 14:26:29 时间
作者:小迅
链接:https://leetcode.cn/problems/coordinate-with-maximum-network-quality/solutions/1942998/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-vlhn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目![](https://img-blog.csdnimg.cn/7be2a4dcec634b41a7aabfdf9ddabaeb.png)
示例![](https://img-blog.csdnimg.cn/c7dfa855e6524d8e84069619d2cf8ff0.png)
思路
题目很长而且不好懂,看懂题目就很容易了
名词解释:
欧几里得距离 不要被“欧几里得”距离整懵,指的就是高中解析几何里两点之间的距离。
数组 towers 中包含一些网络信号塔,其中 towers[i] = [xi, yi, qi] 表示第 i 个网络信号塔的坐标是 (xi, yi) 且信号强度参数为 q,注意towers只是信号塔并不是之后要返回的坐标,我们需要找所有坐标中,信号强度最高的,但是信号强度最高并不一定在信号塔的位置,所有需要遍历所有位置,而且题目规定坐标小于 50 ,那么我们可以枚举所有坐标并计算当前位置的信号强度,最后选择最大值即可,注意在枚举时,我们可以从小到大枚举,这样就不需要考虑字典序因为我们枚举的顺序就是按字典序来的
代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX(a, b) ((a) > (b) ? (a) : (b))
//距离计算
static int mysqrt(int *tower1, int *tower2)
{
return (tower1[0] - tower2[0]) * (tower1[0] - tower2[0]) + (tower1[1] - tower2[1]) * (tower1[1] - tower2[1]);
}
int* bestCoordinate(int** towers, int towersSize, int* towersColSize, int radius, int* returnSize){
int *ans = (int *)malloc(sizeof(int) * 2);
memset(ans, 0, sizeof(ans));
*returnSize = 2;
int max = 0;//初始化
for(int i = 0; i <= 50; ++i) {
for(int j = 0; j <= 50; ++j) {//枚举所有点
int sum = 0;
int d = 0;
int temp[2] = {i,j};
for(int j = 0; j < towersSize; ++j) {//枚举所有信号塔
if((d = mysqrt(temp, towers[j])) <= radius * radius) {
sum += (int)(towers[j][2] / (1 + pow(d,0.5)));//累加所有信号值
}
}
if(max < sum)
{//保存最大小标
memcpy(ans, temp, sizeof(temp));
max = sum;
}
}
}
return ans;
}
作者:小迅
链接:https://leetcode.cn/problems/coordinate-with-maximum-network-quality/solutions/1942998/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-vlhn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关文章
- LeetCode 7. 整数反转
- 笨方法刷 leetcode(一)
- [LeetCode] 1223. Dice Roll Simulation 掷骰子模拟
- [LeetCode] 879. Profitable Schemes 盈利方案
- [LeetCode] 552. Student Attendance Record II 学生出勤记录之二
- [LeetCode] Combine Two Tables 联合两表
- [LeetCode] 169. Majority Element 求大多数
- LeetCode平衡二叉树
- Leetcode——17. Letter Combinations of a Phone Number