题目描述

集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。给定一个数组 nums 代表了集合 S 发生错误后的结果。请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

链接:https://leetcode-cn.com/problems/set-mismatch

示例1

  1. 输入:nums = [1,2,2,4]
  2. 输出:[2,3]

示例2

  1. 输入:nums = [1,1]
  2. 输出:[1,2]

解题思路

这道题看着十分简单,但有一些细节需要注意,首先这个数组包含的是1~n的整数,数组长度也是n,因此我们可以采用一个hash表进行记录,然后再从1~n进行遍历,不存在hash表中的即为missing,出现次数大于1的即为dup

  1. class Solution {
  2. public:
  3. //O(n) O(n)
  4. vector<int> findErrorNums(vector<int>& nums) {
  5. unordered_map<int, int> record;
  6. int dup, missing;
  7. for (auto nu : nums) {
  8. if (record.count(nu) == 0)
  9. record[nu] = 1;
  10. else
  11. record[nu] = 2;
  12. }
  13. for (int i=1; i<=nums.size(); i++) {
  14. if (record.count(i)==0)
  15. missing = i;
  16. if (record[i] == 2)
  17. dup = i;
  18. }
  19. return {dup, missing};
  20. }
  21. };