LeetCode C++ 1184. Distance Between Bus Stops【Array/字首和】簡單
阿新 • • 發佈:2021-01-19
A bushas n
stops numbered from 0
to n - 1
that forma circle. We know the distance between all pairs of neighboring stops where distance[i]
is the distance between the stops numberi
and (i + 1) % n
.
The bus goes along both directionsi.e. clockwise and counterclockwise. Return the shortest distance between the givenstart
destination
stops.
Example 1:
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
Example 2:
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
Example 3:
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
Constraints:
1 <= n<= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
題意:環形公交路線上有 n
個站,按次序從 0
到 n - 1
進行編號,distance[i]
i
的車站和編號為 (i + 1) % n
的車站之間的距離。環線上的公交車都可以按順時針和逆時針的方向行駛。返回乘客從出發點 start
到目的地 destination
之間的最短距離。
解法1 往兩邊掃描
class Solution {
public:
int distanceBetweenBusStops(vector<int>& dist, int s, int d) {
int n = dist.size(), left = dist[d], right = 0;
for (int i = (s - 1 + n) % n; i != d; i = (i - 1 + n) % n) left += dist[i]; //往左走
for (int i = s; i != d; i = (i + 1) % n) right += dist[i]; //往右走
return min(left, right);
}
};
執行效率如下:
執行用時:4 ms, 在所有 C++ 提交中擊敗了98.68% 的使用者
記憶體消耗:8.4 MB, 在所有 C++ 提交中擊敗了97.34% 的使用者
解法2 字首和
如果要多次查詢同一條環形公交車路線上的某兩個站點間最短距離,可以先使用字首和進行預處理:
class Solution {
public:
int distanceBetweenBusStops(vector<int>& dist, int s, int d) {
if (s > d) swap(s, d); //必不可少
int n = dist.size();
vector<int> psum(n + 1); //lsum[i]表示dist[0:i)區間和,即從0到i的距離
for (int i = 0; i < n; ++i) psum[i + 1] = psum[i] + dist[i];
int right = psum[d] - psum[s], left = psum[n] - right;
return min(left, right);
}
};
執行效率如下:
執行用時:8 ms, 在所有 C++ 提交中擊敗了68.42% 的使用者
記憶體消耗:8.6 MB, 在所有 C++ 提交中擊敗了93.36% 的使用者