Python 基礎知識簡單

找出數組中最長的回文

「尋找數組中最長的回文」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 longest_palindrome(arr) ,它接受正整數列表並傳回數組中數字形成回文的最大數字。回文數向前和向後讀起來相同(例如,121、1331、7)。如果不存在回文數,則傳回-1。

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

範例

Example 1
Input
arr = [12, 121, 33, 456, 1331]
Output
1331
Explanation

Palindromic numbers: 121, 33, 1331. The largest is 1331.

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

None of 10, 20, 30 are palindromes (10 reversed is 01 which is 1, not 10).

Example 3
Input
arr = [7, 11, 22, 123]
Output
22
Explanation

Palindromic numbers: 7, 11, 22. The largest is 22.

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

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