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

看板Marginalman作者 (caster )時間1年前 (2024/01/22 15:31), 編輯推噓2(200)
留言2則, 2人參與, 1年前最新討論串617/719 (看更多)
※ 引述《JerryChungYC (JerryChung)》之銘言: : https://leetcode.com/problems/set-mismatch : 645. Set Mismatch : 有一組1~n的整數set,但有一個數字重複與一個數字丟失了,找出重複與缺失的數回傳。 : Example 1: : Input: nums = [1,2,2,4] : Output: [2,3] : Example 2: : Input: num = [1,1] : Output: [1,2] : 思路: : 1. 做一個1~n組成的set,利用差集找出缺失的數 : 2. 用Counter找出出現2次的數 : Python3 code: : -------------------------------------- : class Solution: : def findErrorNums(self, nums: List[int]) -> List[int]: : range_list = set(range(1, len(nums) + 1)) : counter = Counter(nums) : return [[_ for _ in counter if counter[_] == 2][0], : list(range_list - set(nums))[0]] : 後來看其他人的答案,可以用數學計算總合相減得到結果 : 前兩天的有想法但都會遇到TLE 好麻煩 Python3 code: class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: a = [i for i in range(1,len(nums)+1)] dic = {} repetition = 0 for num in nums: if num in dic: repetition = num break else: dic[num] = 1 missing = list(set(a) - set(nums)) return [repetition,missing[0]] 速度不錯但空間超爛 想法差不多 我本來想用xor解這題 因為題目說數列是從1開始 開個迴圈從1->n 然後跟nums[i-1]做xor比較 很快就能找出答案 結果測資有從n->1 哭阿 等等看一下別人的寫法 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.137.25 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1705908675.A.BAF.html

01/22 15:37, 1年前 , 1F
大師
01/22 15:37, 1F

01/22 15:38, 1年前 , 2F
大師
01/22 15:38, 2F
文章代碼(AID): #1bhXd3kl (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bhXd3kl (Marginalman)