(This question is a variation of the LeetCode question 1779. Find Nearest Point That Has the Same X or Y Coordinate . If you haven't completed that question yet, it is recommended to solve it first.)
Given a list of cities with their (x, y) coordinates. For each queried city, find the nearest city that shares the same x or y coordinate. The distance between two cities is calculated using Manhattan distance. If there are multiple possible answers with the same distance, return the one that is lexicographically smallest. If such a city does not exist, return an empty string.
Note that the Manhattan distance between two coordinates and is calculated as .
Implement the CityMap class:
CityMap(String[] cities, int[] xCoordinates, int[] yCoordinates)Initialize the cities with names,xcoordinates andycoordinates.String getNearestCity(String query)Return the name of the nearest city for the queried city name.
Constraints:
- The number of cities will be in the range [1,
]. - All city names are unique and consist of uppercase and lowercase English letters.
- Coordinates are integers within the range [
,].
Example 1:
Input: [ [ ["London", "Toronto", "Ajax", "York", "Bayshore", "Paris", "Leduc", "Chicago"], [0, 1, 2, 4, 5, 0, 1, 0], [1, 2, 5, 3, 4, 2, 0, 0] ], ["London"], ["Toronto"], ["York"], ["Albert"] ]
Output: [null, "Chicago", "Paris", "", ""]
Explanation:
CityMap cityMap = new CityMap(cities, xCoordinates, yCoordinates)getNearestCity("London")// Return "Chicago". Cities sharingx = 0ory = 1are "Paris", and "Chicago", both at a distance of 1. "Chicago" is lexicographically smaller than "Paris".getNearestCity("Toronto")// Returns "Paris". Cities sharingx = 1ory = 2are "Leduc", and "Paris". Paris is the closest with a distance of 1.getNearestCity("York")// Return "". No other city sharesx = 4ory = 3getNearestCity("Albert")//Return "", because "Albert" is not in the list.
