集合 s
包含从 1
到 n
的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums
代表了集合 S
发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
示例 1:
输入:nums = [1,2,2,4]
输出:[2,3]
示例 2:
输入:nums = [1,1]
输出:[1,2]
提示:
2 <= nums.length <= 104
1 <= nums[i] <= 104
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Solution645 {
public int[] findErrorNums(int[] nums) {
ArrayList<Integer> aout = new ArrayList<Integer>();
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
// Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (hm.containsKey(nums[i])) {
hm.put(nums[i], hm.get(nums[i]) + 1);
} else {
hm.put(nums[i], 1);
}
}
for (int i = 1; i <= nums.length; i++) {
if (hm.containsKey(i)) {
if (hm.get(i) > 1) {
aout.add(i);
}
}
}
for (int i = 1; i <= nums.length; i++) {
if (!hm.containsKey(i)) {
aout.add(i);
}
}
int[] out = new int[aout.size()];
for (int i = 0; i < out.length; i++) {
out[i] = aout.get(i);
}
return out;
}
public static void main(String[] args) {
Solution645 sol = new Solution645();
int[] nums = { 1, 2, 2, 4 };
System.out.println(Arrays.toString(sol.findErrorNums(nums)));
}
}