当前位置: 首页 > article >正文

LeetCode:1184. 公交站间的距离 一次遍历数组,复杂度O(n)

1184. 公交站间的距离

today 1184 公交站间的距离

题目描述

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

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

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

  • 1 <= n <= 10^4
  • distance.length == n
  • 0 <= start, destination < n
  • 0 <= distance[i] <= 10^4

题目解析

这道题目是一道关于环形公交路线的题目。

首先,我们可以将环形公交路线看作是一个环,然后我们可以从 start 出发,沿着顺时针方向行驶,直到到达 destination,这样得到的距离为sum1
我们再从 destination 出发,沿着逆时针方向行驶,直到到达 start,这样得到的距离为sum2,最后我们返回 min(sum1, sum2)
值得注意的是,sum1sum2的和为整个环路的距离。因此我们可以通过一次遍历,解决问题。

复杂度分析:

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

代码实现

Python版本:

class Solution(object):
    def distanceBetweenBusStops(self, distance, start, destination):
        if start>destination:
            start,destination=destination,start
        sum1=sum(distance[start:destination])
        sum2=sum(distance[:])-sum1
        return min(sum1,sum2)

C++版本:

class Solution {
public:
    int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
        if (start > destination) {
            swap(start, destination);
        }
        int sum1=0,sum2=0;
        for(int i=0;i<distance.size();i++){
            if(i>=start&&i<destination)
                sum1+=distance[i];
            else
                sum2+=distance[i];
        }
        return min(sum1,sum2);
    }
};

Go版本:

func distanceBetweenBusStops(distance []int, start, destination int) int {
    if start > destination {
        start, destination = destination, start
    }
    sum1, sum2 := 0, 0
    for i, j := range distance {
        if start <= i && i < destination {
            sum1 += j
        } else {
            sum2 += j
        }
    }
    return min(sum1, sum2)
}


http://www.kler.cn/news/308506.html

相关文章:

  • Comsol 利用多孔材料填充复合吸声器,拓宽低频完美吸声
  • 【我的 PWN 学习手札】Unsortedbin Attack
  • Chrome谷歌浏览器登录账号next无反应
  • C++ 重点的关键字
  • vue嵌入第三方页面
  • Java中分布式锁
  • mac新手入门(快捷键)
  • Vue面试题4
  • 缺陷(Bug)的一生
  • 【iOS】UIViewController的生命周期
  • 校园管理系统创新:Spring Boot框架应用案例
  • 文心智能体 城市印象之漫行北京 开发分享
  • 大舍传媒-日本媒体发稿推荐今日东京tokyotoday
  • grep 命令:文本搜索
  • 无畏契约 (Valorant)YOLO 模型数据集
  • 在Unity UI中实现UILineRenderer组件绘制线条
  • 音视频直播应用场景探讨之RTMP推流还是GB28181接入?
  • 仓储管理系统的设计与实现SSM框架
  • python数据分析 pandas库-数据的读取和保存
  • 【Linux 从基础到进阶】KVM虚拟化配置与管理
  • unity3d入门教程四
  • SprinBoot+Vue宠物寄养系统的设计与实现
  • PCL 曲线点云提取
  • Qt常用控件——QTextEdit
  • FPGA编程指南: CSU DMA传输
  • el-table表格的展开行,初始化的时候展开哪一行+设置点击行可展开功能
  • Python爬虫之bs4模块用法
  • 如何用python做一个计算器
  • 基于AlexNet实现猫狗大战
  • 轻松上手Cursor,体验丝滑编程