精華區beta Marginalman 關於我們 聯絡資訊
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
pandix: 大師 10/23 15:39
NTHUlagka: 大師 10/23 16:05