题目地址:
https://leetcode.com/problems/distance-between-bus-stops/
有 n n n个车站,在一个环上,给定相邻站的距离,再给定两个不同的站点。车可以沿着顺时针或逆时针走(方向中途不能变),问从起点到终点的最短距离。
代码如下:
public class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int s1 = 0, s2 = 0;
for (int i = start; i != destination; i = (i + 1) % distance.length) {
s1 += distance[i];
}
for (int i = destination; i != start ; i = (i + 1) % distance.length) {
s2 += distance[i];
}
return Math.min(s1, s2);
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。