A bus has n
stops numbered from 0
to n - 1
that form a circle. We know the distance between all pairs of neighboring stops where distance[i]
is the distance between the stops number i
and (i + 1) % n
.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start
and 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個公交站形成了一個環,它們之間的距離用一個數組 distance 表示,其中 distance[i] 表示公交站i和 (i+1)%n
之間的距離。說是公交可以順時針和逆時針的開,問給定的任意起點和終點之間的最短距離。對於一道 Easy 題的身價,沒有太多的技巧而言,主要就是考察了一個循環數組,求任意兩個點之間的距離,由於兩個方向都可以到達,那么兩個方向的距離加起來就正好是整個數組之和,所以只要求出一個方向的距離,另一個用總長度減去之前的距離就可以得到。所以這里先求出所有數字之和,然后要求出其中一個方向的距離,由於處理循環數組比較麻煩,所以這里希望 start 小於 destination,可以從二者之間的較小值遍歷到較大值,累加距離之和,然后比較這個距離和,跟總距離減去該距離所得結果之間的較小值返回即可,參見代碼如下:
解法一:
class Solution {
public:
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
int total = accumulate(distance.begin(), distance.end(), 0), cur = 0, mx = max(start, destination);
for (int i = min(start, destination); i < mx; ++i) {
cur += distance[i];
}
return min(cur, total - cur);
}
};
我們也可以只要一次遍歷就可以完成,因為最終都要是要遍歷所有的站點距離,當這個站點在 [start, destination) 范圍內,就累加到 sum1 中,否則就累加到 sum2 中。不過要要注意的是要確保 start 小於 destination,所以可以開始做個比較,若不滿足則交換二者。最終返回 sum1 和 sum2 中較小者即可,參見代碼如下:
解法二:
class Solution {
public:
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
int sum1 = 0, sum2 = 0, n = distance.size();
if (start > destination) swap(start, destination);
for (int i = 0; i < n; ++i) {
if (i >= start && i < destination) {
sum1 += distance[i];
} else {
sum2 += distance[i];
}
}
return min(sum1, sum2);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1184
參考資料:
https://leetcode.com/problems/distance-between-bus-stops/
https://leetcode.com/problems/distance-between-bus-stops/discuss/377568/C%2B%2B-one-pass