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

LeetCode 3379: Transformed Array

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

基本資料
#

難易度: easy 第一次嘗試:2026-02-05

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

解題思路
#

正數往右、負數往左走 |nums[i]| 步,兩種情況合起來就是走到 i + nums[i]。環狀陣列用 % n 繞回來(Array 模板五);Python 的 % 對負數會回傳 0..n-1,所以不用分開處理。nums[i] == 0 時落在自己,結果就是 0,也一起處理了。

我的解法
#

class Solution:
    def constructTransformedArray(self, nums: List[int]) -> List[int]:
        n = len(nums)
        return [nums[(i + x) % n] for i, x in enumerate(nums)]

我當時把正、負、零分成三種情況,結果一樣。

複雜度
#

時間 O(n),空間 O(n)(輸出)。

要特別避免的錯誤
#

  • 其他語言的 % 對負數可能回傳負值,要寫成 ((i + x) % n + n) % n。

面試口說整理
#

往右或往左走都等於走到 i + nums[i],環狀陣列取 mod n 就好;Python 的 mod 對負數也是非負的。時間 O(n)。

相關文章

LeetCode 3701: Compute Alternating Sum
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 3701 解題筆記:偶數 index 加、奇數 index 減;用切片就是 sum(nums[::2]) - sum(nums[1::2])
LeetCode 3688: Bitwise OR of Even Numbers in an Array
·1 分鐘
LeetCode Easy Bit-Manipulation Array Simulation
LeetCode 3688 解題筆記:只對偶數做 OR;初始值 0 剛好也是「沒有偶數」時的答案
LeetCode 1920: Build Array from Permutation
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 1920 解題筆記:照定義 ans[i] = nums[nums[i]];要 O(1) 額外空間時,把新值乘 n 疊在原本的值上
LeetCode 3069: Distribute Elements Into Two Arrays I
·1 分鐘
LeetCode Easy Array Two-Pointers Simulation
LeetCode 3069 解題筆記:照規則模擬:前兩個各放一邊,之後比較兩個陣列的最後一個,放到最後一個比較大的那邊
LeetCode 682: Baseball Game
·1 分鐘
LeetCode Easy Array Stack Simulation
LeetCode 682 解題筆記:用 stack 存有效的分數,C 刪掉最後一個,D 加入兩倍,+ 加入最後兩個的和
LeetCode 3507: Minimum Pair Removal to Sort Array I
·1 分鐘
LeetCode Easy Simulation Array
LeetCode 3507 解題筆記:n 很小直接模擬,切片賦值右邊要是 list