1、题目
链接
环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。 环线上的公交车都可以按顺时针和逆时针的方向行驶。 返回乘客从出发点 start 到目的地 destination 之间的最短距离。
示例:
输入:distance = [1,2,3,4], start = 0, destination = 3
输出:4
解释:公交站 0 和 3 之间的距离是 6 或 4,最小值是 4。
提示:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
2、分析
题目要求计算从起点到终点的最小距离,但是题目并没有规定移动的方向,可以顺时针移动也可以逆时针移动,所需要考虑顺时针移动和逆时针移动的最小值。但是,在这里使用一个简单的思想,就是步去考虑方向,只考虑长度的大小,这里我们选择将当start>destination时,将二者的位置进行交换,这样的话计算交换后的距离,然后利用subdistance也就是全图的总的距离,减去二者相差的距离,也就是不移动的距离,就是顺时针的距离,而此时的间隔就是逆时针的距离.
3、代码
class Solution:
def distanceBetweenBusStops(self, distance, start, destination):
sumdistance = sum(distance)
res = 0
if start > destination:
start,destination = destination,start
while start < destination:
res += distance[start]
start += 1
return min(res,sumdistance-res)
4、结果
执行用时 :44 ms, 在所有 Python3 提交中击败了98.87% 的用户
内存消耗 :14.2 MB, 在所有 Python3 提交中击败了100.00%的用户
5、优化
这种思想在处理一些向量问题时,可以转换为一个标量问题,这样可以大大较少我们的程序的复杂度.
望您:
“情深不寿,强极则辱,谦谦君子,温润如玉”。