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

LeetCode 908: Smallest Range I

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

基本資料
#

難易度: easy 第一次嘗試:2022-09-25

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

解題思路
#

只有最大值和最小值重要(Math 模板四):最大值最多降 k、最小值最多升 k,差距最多縮小 2k;其他數都夾在中間,可以跟著調到範圍內。差距不會小於 0。

我的嘗試
#

前四版寫成 max + min 而不是 max - min;改成相減之後,差距大於 2k 時忘了扣掉 2k:[9, 0]、k = 3 答案 3,回傳 9。

正確解法
#

class Solution:
    def smallestRangeI(self, nums: List[int], k: int) -> int:
        return max(0, max(nums) - min(nums) - 2 * k)

複雜度
#

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

要特別避免的錯誤
#

  • 是最大值減最小值,再扣掉 2k。

面試口說整理
#

只有最大值和最小值重要,最大值往下 k、最小值往上 k,差距最多縮小 2k,不會小於 0,所以答案是 max(0, max - min - 2k)。時間 O(n)。

相關文章

LeetCode 914: X of a Kind in a Deck of Cards
·1 分鐘
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 解題筆記:每種卡片的張數都要能被同一個 X >= 2 整除,也就是所有張數的 GCD >= 2
LeetCode 892: Surface Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 解題筆記:每疊 v 個方塊有 4v + 2 個面,再扣掉跟上方和左方相鄰的疊重疊的 2 × min 面
LeetCode 883: Projection Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 解題筆記:俯視是非 0 的格子數,正視和側視分別是每一列、每一欄的最大值總和
LeetCode 812: Largest Triangle Area
·1 分鐘
LeetCode Easy Array Math Geometry Polygons
LeetCode 812 解題筆記:點最多 50 個,枚舉所有三點組合,用鞋帶公式算面積取最大
LeetCode 628: Maximum Product of Three Numbers
·1 分鐘
LeetCode Easy Array Math Sorting
LeetCode 628 解題筆記:排序後答案只有兩種可能:最大的三個相乘,或最小的兩個(負數)乘最大的一個
LeetCode 598: Range Addition II
·1 分鐘
LeetCode Easy Array Math
LeetCode 598 解題筆記:每次操作都包含左上角,被加最多次的是所有操作的交集:min(a) × min(b)