1184. 公交站間的距離
- 1 題目描述
- 2 示例描述
- 2.1 示例1
- 2.2 示例2
- 2.3 示例3
- 3 解題提示
- 4 解題思路
- 5 源碼詳解(C++)
1 題目描述
環形公交路線上有 n 個站,按次序從 0 到 n - 1 進行編号。我們已知每一對相鄰公交站之間的距離,distance[i] 表示編号為 i 的車站和編号為 (i + 1) % n 的車站之間的距離。
環線上的公共汽車都可以按順時針和逆時針的方向行駛。
傳回乘客從出發點 start 到目的地 destination 之間的最短距離。
2 示例描述
2.1 示例1
輸入:distance = [1,2,3,4], start = 0, destination = 1
輸出:1
解釋:公交站 0 和 1 之間的距離是 1 或 9,最小值是 1。
2.2 示例2
輸入:distance = [1,2,3,4], start = 0, destination = 2
輸出:3
解釋:公交站 0 和 2 之間的距離是 3 或 7,最小值是 3。
2.3 示例3
輸入:distance = [1,2,3,4], start = 0, destination = 3
輸出:4
解釋:公交站 0 和 3 之間的距離是 6 或 4,最小值是 4。
3 解題提示
4 解題思路
5 源碼詳解(C++)
class Solution {
public:
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
int res = 0 ;
int sumPath = 0 ;
int abres = 0 ;
for ( int i = 0 ; i < distance.size() ; i ++ )
{
sumPath += distance[i] ;
}
if ( start < destination )
{
for ( int i = start ; i < destination ; i ++ )
{
res += distance[i] ;
}
}
else
{
for ( int i = destination ; i < start ; i ++ )
{
res += distance[i] ;
}
}
abres = sumPath - res ;
if ( abres < res )
{
return abres ;
}
return res ;
}
};