🔗 🟢 4125. Find the Mirror Exception

Problem Statement

題目簡述

給定一個整數陣列 nums\text{nums}。若將某個元素 x∈numsx \in \text{nums} 的十進位數字反轉(忽略前導零)後得到的整數不在 nums\text{nums} 中,則稱 xx 為鏡像例外(Mirror Exception)。

請回傳這個鏡像例外的值;若不存在則回傳 −1-1。題目保證 nums\text{nums} 中至多只有一種相異數值是鏡像例外(即使它出現多次)。

Constraints

約束條件

  • 1≤nums.length≤1001 \le \text{nums.length} \le 100
  • 1≤nums[i]≤1001 \le \text{nums}[i] \le 100
  • 保證 nums\text{nums} 中至多只有一種相異數值為鏡像例外

思路:雜湊集合 + 數字反轉

核心問題是快速判斷每個元素的數字反轉結果是否出現在陣列中。先將 nums\text{nums} 的所有元素存入雜湊集合 vis\textit{vis},後續每次查詢就能在平均 O(1)\mathcal{O}(1) 時間內完成。

接著遍歷陣列中的每個整數 xx,反覆取十進位末位數字並累加構造出反轉後的整數 yy(每次令 y←10y+(v mod 10)y \leftarrow 10y + (v \bmod 10)、v←⌊v/10⌋v \leftarrow \lfloor v / 10 \rfloor)。這種數值反轉方式天然會略過原數字尾端的 00(亦即反轉後的前導零,例如 10→110 \to 1)。

一旦發現 y∉visy \notin \textit{vis},由於題目保證至多只有一種相異數值符合條件,直接回傳 xx 即可;若所有元素的反轉值都在 vis\textit{vis} 中,則回傳 −1-1。

複雜度分析

令 nn 為 nums\text{nums} 的長度,U=max⁡(nums)U = \max(\text{nums})。

  • 時間複雜度:O(nlog⁡U)\mathcal{O}(n \log U)。建立雜湊集合需 O(n)\mathcal{O}(n),每個整數反轉需 O(log⁡10U)\mathcal{O}(\log_{10} U) 時間。
  • 空間複雜度:O(n)\mathcal{O}(n),用於儲存雜湊集合 vis\textit{vis}。

Code

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def findMirrorException(self, nums: list[int]) -> int:
vis = set(nums)
for x in nums:
y = 0
v = x
while v:
v, d = divmod(v, 10)
y = y * 10 + d
if y not in vis:
return x
return -1

寫在最後

Cover Image Credit

The cover image features an artwork created by @坑爹の草神. All rights belong to the original artist.

If you are the copyright holder and prefer it not to be used here, please reach out via email or leave a comment, and I will remove it promptly.