题目描述:
环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。
环线上的公交车都可以按顺时针和逆时针的方向行驶。
返回乘客从出发点 start 到目的地 destination 之间的最短距离。
解题思路:分别计算乘客从start到destination的顺时针和逆时针的距离,只需要考虑边界值即可,最后返回顺时针和逆时针的最短的线路就行。
class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int sun = 0;
int ni = 0;
//计算顺时针需要的距离
for(int i = start;i != destination;i++){
if(i == distance.length){
i = -1;
continue;
}
sun += distance[i];
}
//计算逆时针需要的距离
for(int i = (start - 1) < 0 ? distance.length - 1 : start - 1;i != destination - 1;i--){
if(i == -1){
i = distance.length;
continue;
}
ni += distance[i];
}
//返回最短距离即可
return Math.min(sun,ni);
}
}
- 时间复杂度 : O(n)
- 空间复杂度 : O(n)
优化: 考虑距离循环转圈的时候边界值处理有一点麻烦了,看了解题后发现,从站点6到站点2的距离跟站点2到站点6是一样的,所以可以先判断,把小的值给start。然后取出顺时针需要的站点距离,否则就是逆时针需要的站点距离,也可以用公交循环一次的总距离减去其中顺时针或逆时针的距离。
class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
if(start > destination){ //如果start大就交换值
int temp = start;
start = destination;
destination = temp;
}
int sun = 0;
int ni = 0;
for(int i = 0;i < distance.length;i++){ //循环取出车站的所有距离
if(start <= i && i < destination){ //在顺时针里的就把数据取出来,否则就是逆时针的数据
sun += distance[i];
}else{
ni += distance[i];
}
}
return Math.min(sun,ni);
}
}