Re: [閒聊] 每日LeetCode

作者: Rushia (みけねこ的鼻屎)   2022-10-23 15:26:12
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
作者: pandix (麵包屌)   2022-10-23 15:39:00
大師
作者: NTHUlagka (拉卡)   2022-10-23 16:05:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com