Python 基礎知識簡單

K 個位置的圓週旋轉

“按 K 位置循環旋轉”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 circular_rotate(arr, k),對陣列 arr 執行循環右旋轉 k 位置並傳回結果。元素經過結束環繞移動到開頭。例如,將 [1,2,3,4,5] 右移 2 得到 [4,5,1,2,3]。

約束條件
  • 0 <= len(arr) <= 10^5
  • 0 <= k <= 10^6
  • -10^9 <= arr[i] <= 10^9

範例

Example 1
Input
arr = [1, 2, 3, 4, 5], k = 2
Output
[4, 5, 1, 2, 3]
Explanation

Right rotate by 2: last 2 elements [4,5] move to the front.

Example 2
Input
arr = [10, 20, 30, 40], k = 1
Output
[40, 10, 20, 30]
Explanation

Right rotate by 1: 40 moves to the front.

Example 3
Input
arr = [1, 2, 3], k = 6
Output
[1, 2, 3]
Explanation

k=6 is a multiple of 3 (array length), so the array returns to its original position.

Need a Hint?
考慮使用特定於數組的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。