150強訪談簡單

找到重複的數字

「尋找重複數字」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個包含 n + 1 個整數的整數陣列 nums,其中每個整數都在 [1, n] 範圍內(含)。

nums 中只有一個重複的數字,傳回這個重複的數字。

您必須在不修改陣列 nums 的情況下僅使用恆定的額外空間來解決該問題。

實作一個傳回重複數字的函數 findDuplicate(nums: list) -> int

約束條件
  • 1 <= n <= 100000
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • There is only one repeated number in nums, but it could be repeated more than once

範例

Example 1
Input
[1,3,4,2,2]
Output
2
Explanation

The duplicate number is 2. It appears twice in the array.

Example 2
Input
[3,1,3,4,2]
Output
3
Explanation

The duplicate number is 3. It appears twice in the array.

Example 3
Input
[3,3,3,3,3]
Output
3
Explanation

The duplicate number is 3. It appears five times.

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 資源

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