280. 最近的城市
在一个二维平面上有许多城市,所有的城市都有着自己的名字
c[i]
c
[
i
]
,以及位置坐标
(x[i],y[i])
(
x
[
i
]
,
y
[
i
]
)
(都为整数)。有
q
q
组询问,每组询问给出一个城市名字,你需要回答离该城市距离最近的,
x
x
相同或者
y
y
相同的城市名称。
样例
样例 1:
输入:x = [3, 2, 1] y = [3, 2, 3] c = ["c1", "c2", "c3"] q = ["c1", "c2", "c3"]
输出:["c3", "NONE", "c1"]
解释:对于c1,c3和它y相同,距离最近,为(3-1)+(3-3)=2
对于c2,没有城市和它x相同或y相同
对于c3,c1和他y相同,距离最近,为(3-1)+(3-3)=2
注意事项
若有多种满足条件的答案,输出名字字典序最小的一个。
这里的距离为欧拉距离:
x
x
坐标差的绝对值加
y
y
坐标差的绝对值。
0\leq
0
≤
城市个数
\leq10^5
≤
1
0
5
,
0\leq
0
≤
询问组数
\leq 10
≤
1
0
,
1\leq
1
≤
坐标范围
\leq 10^9
≤
1
0
9
public class Solution {
/**
* @param x: an array of integers, the x coordinates of each city[i]
* @param y: an array of integers, the y coordinates of each city[i]
* @param c: an array of strings that represent the names of each city[i]
* @param q: an array of strings that represent the names of query locations
* @return: the closest city for each query
*/
public String[] NearestNeighbor(int[] x, int[] y, String[] c, String[] q) {
// write your code here
String[] ret = new String[q.length];
int[] xData = new int[q.length];
int[] yData = new int[q.length];
int[] sum = new int[q.length];
int flag = 0;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < q.length; j++) {
if (q[j].equals(c[i])) {
xData[j] = x[i];
yData[j] = y[i];
sum[j] = Integer.MAX_VALUE;
ret[j] = "NONE";
flag++;
}
}
if (flag == q.length) break;
}
int temp;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < xData.length; j++) {
if (xData[j] == x[i]) {
if (yData[j] == y[i]) continue;
temp=Math.abs(yData[j] - y[i]);
if (temp<sum[j]){
ret[j] = c[i];
sum[j]=temp;
}
if (temp==sum[j]){
for (int k = 0; k < c[i].length(); k++) {
if (c[i].charAt(k)<ret[j].charAt(k)){
ret[j] = c[i];
break;
}
}
}
} else if (yData[j] == y[i]) {
temp=Math.abs(xData[j] - x[i]);
if (temp<sum[j]){
ret[j] = c[i];
sum[j]=temp;
}
if (temp==sum[j]){
for (int k = 0; k < c[i].length(); k++) {
if (c[i].charAt(k)<ret[j].charAt(k)){
ret[j] = c[i];
break;
}
}
}
}
}
}
return ret;
}
}