集合 S 包含從1到 n 的整數。不幸的是,因爲數據錯誤,導致集合裏面某一個元素複製了成了集合裏面的另外一個元素的值,導致集合丟失了一個整數並且有一個元素重複。
給定一個數組 nums 代表了集合 S 發生錯誤後的結果。你的任務是首先尋找到重複出現的整數,再找到丟失的整數,將它們以數組的形式返回。
示例 1:
輸入: nums = [1,2,2,4]
輸出: [2,3]
注意:
給定數組的長度範圍是 [2, 10000]。
給定的數組是無序的。
思考:
這一題也不難,按照題目的描述,先尋找到重複出現的整數,再找到丟失的整數,這是最簡單的思路
public int[] findErrorNums(int[] nums) {
Set<Integer> set = new HashSet<>();
int[] result = new int[2];
// 先尋找到重複出現的整數
for (int num : nums) {
if (!set.add(num)) {
result[0] = num;
}
}
// 再找到丟失的整數
for (int i = 1; i <= nums.length; i++) {
if (!set.contains(i)) {
result[1] = i;
}
}
return result;
}
利用Set的特性很簡單就完成了,但是效率不高。
更高效的思路是:
因爲nums包含的是從1到n的整數,那麼構建一個初始爲0的數組array,遍歷nums,將nums中數作爲下標對應到array的值自增一次。這樣nums中出現兩次的數就是array中2的下標,而丟失的數就是array中0的下標。
public int[] findErrorNums(int[] nums) {
int[] array = new int[nums.length + 1];
for (int i : nums) {
array[i]++;
}
int[] result = new int[2];
for (int i = 1; i < array.length; i++) {
// nums中出現兩次的數就是array中2的下標
if (array[i] == 2) {
result[0] = i;
}
// nums丟失的數就是array中0的下標
if (array[i] == 0) {
result[1] = i;
}
}
return result;
}