Approach
Direct simulation
For Find the City With the Smallest Number of Neighbors at a Threshold Distance, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.
- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 44 lines of Java from the credited upstream file 1334.java.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int findTheCity(int n, int[][] edges, int distanceThreshold) {3 int ans = -1;4 int minCitiesCount = n;5 int[][] dist = floydWarshall(n, edges, distanceThreshold);6 7 for (int i = 0; i < n; ++i) {8 int citiesCount = 0;9 for (int j = 0; j < n; ++j)10 if (dist[i][j] <= distanceThreshold)11 ++citiesCount;12 if (citiesCount <= minCitiesCount) {13 ans = i;14 minCitiesCount = citiesCount;15 }16 }17 18 return ans;19 }20 21 private int[][] floydWarshall(int n, int[][] edges, int distanceThreshold) {22 int[][] dist = new int[n][n];23 Arrays.stream(dist).forEach(A -> Arrays.fill(A, distanceThreshold + 1));24 25 for (int i = 0; i < n; ++i)26 dist[i][i] = 0;27 28 for (int[] edge : edges) {29 final int u = edge[0];30 final int v = edge[1];31 final int w = edge[2];32 dist[u][v] = w;33 dist[v][u] = w;34 }35 36 for (int k = 0; k < n; ++k)37 for (int i = 0; i < n; ++i)38 for (int j = 0; j < n; ++j)39 dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);40 41 return dist;42 }43}44