【112】
1620. 网络信号最好的坐标
给你一个数组 towers 和一个整数 radius 。
数组 towers 中包含一些网络信号塔,其中 towers[i] = [xi, yi, qi] 表示第 i 个网络信号塔的坐标是 (xi, yi) 且信号强度参数为 qi 。所有坐标都是在 X-Y 坐标系内的 整数 坐标。两个坐标之间的距离用 欧几里得距离 计算。
整数 radius 表示一个塔 能到达 的 最远距离 。如果一个坐标跟塔的距离在 radius 以内,那么该塔的信号可以到达该坐标。在这个范围以外信号会很微弱,所以 radius 以外的距离该塔是 不能到达的 。
如果第 i 个塔能到达 (x, y) ,那么该塔在此处的信号为 ⌊qi / (1 + d)⌋ ,其中 d 是塔跟此坐标的距离。一个坐标的 信号强度 是所有 能到达 该坐标的塔的信号强度之和。
请你返回数组 [cx, cy] ,表示 信号强度 最大的 整数 坐标点 (cx, cy) 。如果有多个坐标网络信号一样大,请你返回字典序最小的 非负 坐标。
注意:
- 坐标
(x1, y1)字典序比另一个坐标(x2, y2)小,需满足以下条件之一:- 要么
x1 < x2, - 要么
x1 == x2且y1 < y2。
- 要么
⌊val⌋表示小于等于val的最大整数(向下取整函数)。
示例 1:

输入:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2 输出:[2,1] 解释: 坐标 (2, 1) 信号强度之和为 13 - 塔 (2, 1) 强度参数为 7 ,在该点强度为 ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - 塔 (1, 2) 强度参数为 5 ,在该点强度为 ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - 塔 (3, 1) 强度参数为 9 ,在该点强度为 ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 没有别的坐标有更大的信号强度。
示例 2:
输入:towers = [[23,11,21]], radius = 9 输出:[23,11] 解释:由于仅存在一座信号塔,所以塔的位置信号强度最大。
示例 3:
输入:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2 输出:[1,2] 解释:坐标 (1, 2) 的信号强度最大。
-------------------------------------------------------------------------------------------------
代码如下:
1 class Solution { 2 public int[] bestCoordinate(int[][] towers, int radius) { 3 //用于记录xy坐标的最大值 4 int xMax = 0; 5 int yMax = 0; 6 for(int[] tower : towers){ 7 xMax = Math.max(xMax, tower[0]); 8 yMax = Math.max(yMax, tower[1]); 9 } 10 //将范围内每一点的信号强度都算出来,比较大小 11 int cx = 0; 12 int cy = 0; 13 int maxStrength = 0; 14 for(int x = 0; x <= xMax; x++){ 15 for(int y = 0; y <= yMax; y++){ 16 int target[] = {x, y}; 17 int strength = 0; 18 for(int[] tower : towers){ 19 int distance = getDistance(target, tower); 20 if(distance <= radius * radius){ 21 strength += Math.floor(tower[2]/(1 + Math.sqrt(distance)));//Math.floor是向下取整函数 22 } 23 } 24 //由于是从0开始遍历,只取字典序小的最大信号强度,之后与他相同的直接排除 25 if(strength > maxStrength){ 26 cx = x; 27 cy = y; 28 maxStrength = strength; 29 } 30 31 } 32 } 33 34 return new int[]{cx, cy}; 35 36 } 37 38 public int getDistance(int[] target, int[] tower){ 39 return (tower[0] - target[0]) * (tower[0] - target[0]) + (tower[1] - target[1]) * (tower[1] - target[1]); 40 } 41 42 }
-------------------------------------------------------------------------------------------------
由于数据量较小(坐标<50),也可以把0-50的所有坐标遍历,暴力破解。

浙公网安备 33010602011771号