Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (caster)時間1年前 (2024/05/31 11:50), 1年前編輯推噓5(509)
留言14則, 5人參與, 1年前最新討論串300/1554 (看更多)
https://leetcode.com/problems/single-number-iii 260. Single Number III 給定一數列 此數列只有兩個數字單獨出現 其他元素都成雙成對 請回傳單獨出現的兩個數字 Example 1: Input: nums = [1,2,1,3,2,5] Output: [3,5] Explanation: [5, 3] is also a valid answer. Example 2: Input: nums = [-1,0] Output: [-1,0] Example 3: Input: nums = [0,1] Output: [1,0] Constraints: 2 <= nums.length <= 3 * 104 -231 <= nums[i] <= 231 - 1 Each integer in nums will appear twice, only two integers will appear once. 思路: 哈希表紀錄出現次數 Python Code: class Solution: def singleNumber(self, nums: List[int]) -> List[int]: res = [] map = defaultdict(int) for n in nums: map[n] += 1 for k,v in map.items(): if v == 1: res.append(k) if len(res) == 2: return res 應該有位運算解法 但我試不出來 告辭 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.156.128 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1717127432.A.61B.html

05/31 11:51, 1年前 , 1F
別捲了
05/31 11:51, 1F
※ 編輯: sustainer123 (223.137.48.144 臺灣), 05/31/2024 11:51:38

05/31 11:53, 1年前 , 2F
大師
05/31 11:53, 2F

05/31 11:53, 1年前 , 3F
大師
05/31 11:53, 3F

05/31 11:54, 1年前 , 4F
你就先所有數xor一次
05/31 11:54, 4F

05/31 11:54, 1年前 , 5F
接著找出這個結果哪一個位元是1
05/31 11:54, 5F

05/31 11:54, 1年前 , 6F
代表這兩個數在這個位元一個是1一個是0
05/31 11:54, 6F

05/31 11:55, 1年前 , 7F
再來你就依照這個位元去把nums的元素分成兩堆
05/31 11:55, 7F

05/31 11:56, 1年前 , 8F
最後將這兩堆分別xor就可以得到答案了
05/31 11:56, 8F

05/31 11:57, 1年前 , 9F
分成該位元分別是1、0的兩堆
05/31 11:57, 9F

05/31 11:58, 1年前 , 10F
我試試
05/31 11:58, 10F

05/31 11:59, 1年前 , 11F
可是這樣怎麼感覺時間複雜度還不如計數
05/31 11:59, 11F

05/31 11:59, 1年前 , 12F
時間複雜度就O(N)
05/31 11:59, 12F

05/31 12:00, 1年前 , 13F
主要是題目要求不能用extra space
05/31 12:00, 13F

05/31 12:05, 1年前 , 14F
原來
05/31 12:05, 14F
文章代碼(AID): #1cMKa8OR (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cMKa8OR (Marginalman)