leetcode-03 1184. 公交站间的距离

                                         1184. 公交站间的距离

题目:

环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。

环线上的公交车都可以按顺时针和逆时针的方向行驶。

返回乘客从出发点 start 到目的地 destination 之间的最短距离。

示例:

输入:distance = [1,2,3,4], start = 0, destination = 1
输出:1
解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。

解题思路:python切片

代码:

class Solution(object):
    def distanceBetweenBusStops(self, distance, start, destination):
        """
        :type distance: List[int]
        :type start: int
        :type destination: int
        :rtype: int
        """
        sum_distance = sum(distance)
        if start <= destination:
            # 顺时针
            first_distance = sum(distance[start:destination])
        else:
            # 逆时针
            first_distance = sum(distance[destination:start])
    
        return min(first_distance, sum_distance-first_distance)

猜你喜欢

转载自blog.csdn.net/qq_43299522/article/details/108596968