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

LeetCode 3550: Smallest Index With Digit Sum Equal to Index

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

基本資料
#

難易度: easy 第一次嘗試:2025-05-18

  • 提交紀錄:Accepted(一次通過)

解題思路
#

從 index 0 開始,算 nums[i] 的位數和,第一個等於 i 的就是最小的 index;都沒有就回傳 -1。

我的解法
#

class Solution:
    def smallestIndex(self, nums: List[int]) -> int:
        for i, x in enumerate(nums):
            if sum(int(c) for c in str(x)) == i:
                return i
        return -1

複雜度
#

時間 O(n · d),d 是位數,空間 O(d)。

要特別避免的錯誤
#

  • 要回傳最小的 index,從頭掃到第一個就回傳。

面試口說整理
#

由小到大掃每個 index,把數字轉成字串加總位數,第一個等於 index 的就回傳,沒有就回傳 -1。時間 O(n · d)。

相關文章

LeetCode 1979: Find Greatest Common Divisor of Array
·1 分鐘
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 解題筆記:找出最小值和最大值,用輾轉相除法算 GCD
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 989: Add to Array-Form of Integer
·1 分鐘
LeetCode Easy Array Math
LeetCode 989 解題筆記:把 k 當成進位,從陣列最後一位往前加,k 還沒用完就繼續往前補位
LeetCode 908: Smallest Range I
·1 分鐘
LeetCode Easy Array Math
LeetCode 908 解題筆記:最大值往下調 k、最小值往上調 k,答案是 max(0, max - min - 2k)
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 面