问题:
给定n个汽车站之间的距离数组distances(相邻两个站相连,收尾站相连,可顺时针逆时针两个方向行驶)
求start站和destination站之间的最短距离。
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
解法:
从start站到destination站
两个方向行驶的距离 之和=总distance之和。
因此遍历所有distance
left=min(start, destination)
right=max(start, destination)
当 i 在 [left, right)(左闭右开区间)时,为顺时针行驶距离,
剩下距离求和,则为逆时针行驶距离。
最后返回二者较小值。
代码参考:
1 class Solution { 2 public: 3 int distanceBetweenBusStops(vector<int>& distance, int start, int destination) { 4 int res1=0; 5 int res2=0; 6 for(int i=0; i<distance.size(); i++){ 7 if(i>=min(start, destination) && i<max(start, destination)){ 8 res1+=distance[i]; 9 }else{ 10 res2+=distance[i]; 11 } 12 } 13 return min(res1, res2); 14 } 15 };