Advertisement
theSwamz

NearestCities/Pins

Apr 13th, 2021 (edited)
934
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.35 KB | None | 0 0
  1. class Solution {
  2.     static class Pin {
  3.         String name;
  4.         int x;
  5.         int y;
  6.         public Pin(String name_, int x_, int y_) {
  7.             name = name_;
  8.             x = x_;
  9.             y = y_;
  10.         }
  11.         public int dist(Pin otherPin) {
  12.           return Math.abs(x - otherPin.x) + Math.abs(y - otherPin.y);
  13.         }
  14.     }
  15.     public static List<String> nearestPins(List<String> pins, List<Integer> xCoordinates, List<Integer> yCoordinates, List<String> queries) {
  16.         // WRITE YOUR BRILLIANT CODE HERE
  17.         return List.of();
  18.         Map<Integer, ArrayList<Pin>> xTopins = new HashMap<>();
  19.         Map<Integer, ArrayList<Pin>> yTopins = new HashMap<>();
  20.         Map<String, Pin> pinByName = new HashMap<>();
  21.         for (int i = 0; i < pins.size(); i++) {
  22.             String pinName = pins.get(i);
  23.             int x = xCoordinates.get(i);
  24.             int y = yCoordinates.get(i);
  25.             Pin pin = new Pin(pinName, x, y);
  26.             xTopins.computeIfAbsent(x, v -> new ArrayList<>());
  27.             yTopins.computeIfAbsent(y, v -> new ArrayList<>());
  28.             xTopins.get(x).add(pin);
  29.             yTopins.get(y).add(pin);
  30.             pinByName.put(pinName, pin);
  31.         }
  32.         List<String> ans = new ArrayList<>();
  33.         Map<String, String> cache = new HashMap<>();
  34.         for (String name : queries) {
  35.             if (cache.containsKey(name)) {
  36.                 ans.add(cache.get(name));
  37.                 continue;
  38.             }
  39.             Pin pin = pinByName.get(name);
  40.             int minDist = Integer.MAX_VALUE;
  41.             String closest = null;
  42.             List<Pin> searchpins = xTopins.get(pin.x);
  43.             searchpins.addAll(yTopins.get(pin.y));
  44.             for (Pin otherPin : searchpins) {
  45.                 if (otherPin.equals(pin)) {
  46.                     continue;
  47.                 }
  48.                 int dist = pin.dist(otherPin);
  49.                 if (closest == null || dist < minDist || (dist == minDist && otherPin.name.compareTo(closest) < 0)) {
  50.                     minDist = pin.dist(otherPin);
  51.                     closest = otherPin.name;
  52.                 }
  53.             }
  54.             if (closest != null) {
  55.                 ans.add(closest);
  56.                 cache.put(name, closest);
  57.             } else {
  58.                 ans.add("NONE");
  59.             }
  60.         }
  61.         return ans;
  62.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement