版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85524682
Title:Set Mismatch 645
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/set-mismatch/
1. 见代码
时间复杂度:O(n),一次一层for循环,循环最长为n。
空间复杂度:O(n),申请空间n-1个长度的map。
/**
* map存储
* 数学方法: x(x+1)/2
* @param nums
* @return
*/
public static int[] findErrorNums(int[] nums) {
int res[] = new int[2];
Map<Integer, Integer> map = new HashMap<>();
int total = nums.length * (nums.length + 1) / 2;
int numsTotal = 0;
for (int i = 0; i < nums.length; i++) {
numsTotal += nums[i];
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
}
else {
map.put(nums[i], 1);
}
if (map.get(nums[i]) == 2) {
res[0] = nums[i];
}
}
res[1] = total - numsTotal + res[0];
return res;
}