天天看點

1184. 公交站間的距離 : 簡單模拟題

題目描述

這是 LeetCode 上的 ​​1184. 公交站間的距離​​ ,難度為 簡單。

Tag : 「模拟」

環形公交路線上有  個站,按次序從  到  進行編号。我們已知每一對相鄰公交站之間的距離, 表示編号為  的車站和編号為 ​​

​(i + 1) % n​

​ 的車站之間的距離。

環線上的公共汽車都可以按順時針和逆時針的方向行駛。

傳回乘客從出發點 ​

​start​

​​ 到目的地 ​

​destination​

​ 之間的最短距離。

示例 1:

1184. 公交站間的距離 : 簡單模拟題
輸入:distance = [1,2,3,4], start = 0, destination = 1      

示例 2:

1184. 公交站間的距離 : 簡單模拟題
輸入:distance = [1,2,3,4], start = 0, destination = 2      

示例 3:

1184. 公交站間的距離 : 簡單模拟題
輸入:distance = [1,2,3,4], start = 0, destination = 3      

提示:

模拟

根據題意進行模拟即可。

用 ​

​i​

​​ 和 ​

​j​

​​ 分别代表往前和往後走的指針,​

​a​

​​ 和 ​

​b​

​ 分别統計兩種走法的總成本。

Java 代碼:

class Solution {
    public int distanceBetweenBusStops(int[] dist, int s, int {
        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      

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)
};      
  • 時間複雜度:
  • 空間複雜度:

最後

這是我們「刷穿 LeetCode」系列文章的第 ​

​No.1184​

​ 篇,系列開始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道題目,部分是有鎖題,我們将先把所有不帶鎖的題目刷完。

在這個系列文章裡面,除了講解解題思路以外,還會盡可能給出最為簡潔的代碼。如果涉及通解還會相應的代碼模闆。