Python 基礎知識簡單

數組中的所有數字可以相等嗎

“數組的所有數字是否相等”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 can_make_equal(arr) 來決定是否可以透過重複增加或減去另一個元素中的任何元素來使陣列的所有元素相等。當且僅當數組的總和可以被數組的長度整除時(即平均值是整數),這才是可能的。如果可能,則回傳 True,否則傳回 False。注意:更簡單的解釋 - 如果我們可以自由地重新分配值,那麼當總和可被長度整除時,我們總是可以使它們相等。

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

範例

Example 1
Input
arr = [1, 1, 1]
Output
True
Explanation

All elements are already equal.

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

Sum = 6, length = 3. 6/3 = 2. We can make all elements 2.

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

Sum = 7, length = 3. 7/3 is not an integer, so we cannot make all equal.

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

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