645. 錯誤的集合
難度簡單98
集合?S
?包含從1到?n
?的整數。不幸的是,因為數據錯誤,導致集合里面某一個元素復制了成了集合里面的另外一個元素的值,導致集合丟失了一個整數并且有一個元素重復。
給定一個數組?nums
?代表了集合?S
?發生錯誤后的結果。你的任務是首先尋找到重復出現的整數,再找到丟失的整數,將它們以數組的形式返回。
示例 1:
輸入: nums = [1,2,2,4] 輸出: [2,3]
注意:
- 給定數組的長度范圍是?[2, 10000]。
- 給定的數組是無序的。
記錄出現次數即可。
class Solution {public int[] findErrorNums(int[] nums) {int[] resule = new int[2];int[] temp = new int[nums.length+1];for(int num : nums) {temp[num]++;}for(int i = 1; i < temp.length; i++){if(temp[i] == 2)resule[0] = i;if(temp[i] == 0)resule[1] = i;}return resule;}
}
?