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

看板Marginalman作者 (みけねこ的鼻屎)時間3年前 (2022/10/23 15:26), 編輯推噓2(200)
留言2則, 2人參與, 3年前最新討論串59/719 (看更多)
645. Set Mismatch 給予一個陣列表示一個不重複數字的集合,集合的元素範圍為 1~n,但是這邊出現了 錯誤導致集合內存在兩個重複數字,找出集合的重複數字和缺少的數字。 Example: Input: nums = [1,2,2,4] Output: [2,3] 思路: 1.用一個陣列紀錄每個元素的出現次數。 2.遍歷 1~n 檢查數字,分三個case: 0:缺失的數字 1:正常的數字 2:多一個的數字 目標是找0和2的數字是哪個。 3.當res的兩個數字都不為0的時候,表示兩個數字都找到了,提早跳出迴圈。 JavaCode: class Solution { public int[] findErrorNums(int[] nums) { int[] res = new int[2]; int[] count = new int[nums.length + 1]; for (int num : nums) count[num]++; for(int i = 1; i < count.length; i++){ if(count[i] != 1){ if(count[i] == 2) res[0] = i; else res[1] = i; if(res[0] != 0 && res[1] != 0) break; } } return res; } } https://i.imgur.com/ZCY3Agm.gif
-- https://i.imgur.com/tdaniED.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.111.108 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1666509974.A.6E2.html

10/23 15:39, 3年前 , 1F
大師
10/23 15:39, 1F

10/23 16:05, 3年前 , 2F
大師
10/23 16:05, 2F
文章代碼(AID): #1ZLEoMRY (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZLEoMRY (Marginalman)