classSolution { public: vector<int> shortestDistanceAfterQueries(int n, vector<vector<int>>& queries){ vector<int> shortest(n); vector<vector<int>> fromList(n); for (int i = 1; i < n; i++) { fromList[i].push_back(i - 1); shortest[i] = i; } vector<int> ans(queries.size()); for (int i = 0; i < queries.size(); i++) { int from = queries[i][0], to = queries[i][1]; fromList[to].push_back(from); for (int j = to; j < n; j++) { for (int from : fromList[j]) { shortest[j] = min(shortest[j], shortest[from] + 1); } } ans[i] = shortest.back(); } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from typing importList
classSolution: defshortestDistanceAfterQueries(self, n: int, queries: List[List[int]]) -> List[int]: shortest = [i for i inrange(n)] fromList = [[i - 1] for i inrange(n)] ans = [] for from_, to in queries: fromList[to].append(from_) for i inrange(to, n): shortest[i] = min(shortest[i], min(shortest[j] + 1for j in fromList[i])) ans.append(shortest[-1]) return ans