↓快轉到主要內容
  1. LeetCode/

LeetCode 1184: Distance Between Bus Stops

·1 分鐘· ·
LeetCode Easy Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-10-18

  • 提交紀錄:Wrong Answer ×4 → Accepted ×4

解題思路
#

環上只有兩條路:順時針走過 distance[a:b](a = min(start, destination)、b = max(...)),逆時針是 總和 - 順時針,取比較短的。先把兩個端點排好,不然 start > destination 時切片是空的。

我的嘗試
#

前四版都沒有處理 start > destination,切片 distance[start:destination] 是空的,順時針算成 0:[2, 2]、start = 1、destination = 0 回傳 0,答案 2。加上交換就 AC 了。

正確解法
#

class Solution:
    def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
        a, b = min(start, destination), max(start, destination)
        clockwise = sum(distance[a:b])
        return min(clockwise, sum(distance) - clockwise)

複雜度
#

時間 O(n),空間 O(1)(切片 O(n))。

要特別避免的錯誤
#

  • start 可能比 destination 大,要先交換。

面試口說整理
#

環狀路線只有兩個方向,我先把起點終點排好,順時針是兩點之間的距離和,逆時針是總和減掉它,取較小的。時間 O(n)。

相關文章

LeetCode 1089: Duplicate Zeros
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 1089 解題筆記:先數有幾個 0 決定每個數要往後移幾格,再從後往前搬,遇到 0 時把複製的那個 0 也寫進去
LeetCode 1122: Relative Sort Array
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 解題筆記:計數後先按照 arr2 的順序輸出,剩下的數由小到大接在後面
LeetCode 1128: Number of Equivalent Domino Pairs
·1 分鐘
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 解題筆記:把每張骨牌正規化成 (小, 大) 當 key 計數,每個 key 有 c 張就有 c(c - 1) / 2 對
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 1046: Last Stone Weight
·1 分鐘
LeetCode Easy Array Heap-Priority-Queue
LeetCode 1046 解題筆記:max-heap(存負數)每次拿出最重的兩顆,不一樣重就把差放回去,最後剩一顆或沒有
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開