iT邦幫忙

0

Day5 Single Number

  • 分享至 

  • xImage
  •  

題目:給定一個整數陣列,除了某一個元素只出現一次以外,其餘每個元素都出現兩次。請找出這個唯一的數字。
https://ithelp.ithome.com.tw/upload/images/20250919/20169339yxzcSp4BE7.jpg

解法一
https://ithelp.ithome.com.tw/upload/images/20250919/20169339aqXHuiRsw1.jpg

以下是因為測試資料很大,像圖片裡幾萬個數字時,程式就會跑太久,超過 LeetCode 的時間限制,所以只能理解用
https://ithelp.ithome.com.tw/upload/images/20250919/2016933933vIZ7VGae.jpg
解法二
https://ithelp.ithome.com.tw/upload/images/20250919/20169339drYfTZGYym.jpg

HashMap / Counter
用字典統計每個數字出現次數,再回傳只出現一次的那個數字。
解法三
https://ithelp.ithome.com.tw/upload/images/20250919/20169339Tuef5BDp0Y.jpg

XOR 位元運算
利用 XOR 的特性:
• a ^ a = 0
• a ^ 0 = a
• XOR 有交換律和結合律
把所有數字 XOR 起來,最後結果就是唯一的那個
最快最省資源


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言