1184. 公交站间的距离 : 简单模拟题

题目描述

这是 LeetCode 上的 1184. 公交站间的距离 ,难度为 简单

Tag : 「模拟」

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

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

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

示例 1:
1184. 公交站间的距离 : 简单模拟题_第1张图片

输入:distance = [1,2,3,4], start = 0, destination = 1

输出:1

解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。

示例 2:
1184. 公交站间的距离 : 简单模拟题_第2张图片

输入:distance = [1,2,3,4], start = 0, destination = 2

输出:3

解释:公交站 0 和 2 之间的距离是 3 或 7,最小值是 3。

示例 3:
1184. 公交站间的距离 : 简单模拟题_第3张图片

输入: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$

模拟

根据题意进行模拟即可。

ij 分别代表往前和往后走的指针,ab 分别统计两种走法的总成本。

Java 代码:

class Solution {
    public int distanceBetweenBusStops(int[] dist, int s, int t) {
        int n = dist.length, i = s, j = s, a = 0, b = 0;
        while (i != t) {
            a += dist[i];
            if (++i == n) i = 0;
        }
        while (j != t) {
            if (--j < 0) j = n - 1; 
            b += dist[j];
        }
        return Math.min(a, b);
    }
}

TypeScript 代码:

function distanceBetweenBusStops(dist: number[], s: number, t: number): number {
    let n = dist.length, i = s, j = s, a = 0, b = 0
    while (i != t) {
        a += dist[i]
        if (++i == n) i = 0
    }
    while (j != t) {
        if (--j < 0) j = n - 1
        b += dist[j]
    }
    return Math.min(a, b)
};
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.1184 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSou...

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。

更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地

本文由mdnice多平台发布

你可能感兴趣的:(后端)