本帖最后由 匿名 于 2021-9-14 23:20 编辑
share 一个solution 求米- public List<String> closestStraightCity(String[] citys, int[] xs, int[] ys, String[] queryCitys) {
- Map<String, int[]> cs = new HashMap<>(); // city name: (x,y)
- Map<Integer, TreeMap<Integer, String>> X = new HashMap<>();
- // x line: y1: city2 name( < city1name) y3: city3 name
- Map<Integer, TreeMap<Integer, String>> Y = new HashMap<>();
- // y line: x1: city1 name, x2: city2 name
- int N = citys.length;
- for (int i = 0; i < N; i++) {
- int x = xs[i], y = ys[i];
- String name = citys[i];
- X.computeIfAbsent(x, k -> new TreeMap<>());
- if (!X.get(x).containsKey(y) || name.compareTo(X.get(x).get(y)) < 0) {
- X.get(x).put(y, name); // lexicographically order name
- }
- Y.computeIfAbsent(y, k -> new TreeMap<>());
- if (!Y.get(y).containsKey(x) || name.compareTo(Y.get(y).get(x)) < 0) {
- Y.get(y).put(x, name); // lexicographically order name
- }
- cs.put(name, new int[] {x, y});
- }
- List<String> r = new ArrayList<>();
- for (String c : queryCitys) {
- int x = cs.get(c)[0], y = cs.get(c)[1];
- List<Choice> four = new ArrayList<>();
- collect(X, x, y, four);
- collect(Y, y, x, four);
- Collections.sort(
- four,
- (a, b) -> {
- if (a.distance == b.distance) return a.name.compareTo(b.name);
- return a.distance - b.distance;
- });
- r.add(four.isEmpty() ? "NONE" : four.get(0).name);
- }
- return r;
- }
- private void collect(Map<Integer, TreeMap<Integer, String>> L, int l, int v, List<Choice> four) {
- if (L.get(l) != null) {
- Map.Entry<Integer, String> hi = L.get(l).higherEntry(v);
- Map.Entry<Integer, String> low = L.get(l).lowerEntry(v);
- if (hi != null) four.add(new Choice(hi.getValue(), hi.getKey() - v));
- if (low != null) four.add(new Choice(low.getValue(), v - low.getKey()));
- }
- }
- class Choice {
- String name;
- int distance;
- public Choice(String name, int distance) {
- this.name = name;
- this.distance = distance;
- }
- }
复制代码 |