# LeetCode 算法題 – Set Mismatch

## 原題

The set S originally contains numbers from 1 to n.
But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set,
which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error.
Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

``````Input: nums = [1,2,2,4]
Output: [2,3]
``````

Note:

• The given array size will in the range [2, 10000].
• The given array’s numbers won’t have any order.

## 分析

• 正確的數組中，每個數字只出現一次，範圍[1,n]
• 找出重複的數字和缺失的數字

• 異或，(1^1)^(2^2)^…^(x)^…^(n^n)，則可知道缺失的數字是x
• Map 是已出現了的數字集合，只需再次遍歷一遍，則可得到缺失的數字

## 實現

### 實現一

`````` 1func findErrorNums(nums []int) []int {
2    m := make(map[int]bool, len(nums))
3    v := make([]int, 2)
4
5    for i := 0; i < len(nums); i++ {
6        v[1] ^= i + 1
7        if m[nums[i]] {
8            v[0] = nums[i]
9        } else {
10            m[nums[i]] = true
11            v[1] ^= nums[i]
12        }
13    }
14
15    return v
16}
``````

### 實現二

`````` 1func findErrorNums(nums []int) []int {
2    m := make(map[int]bool, len(nums))
3    v := make([]int, 2)
4
5    for _, num := range nums {
6        if m[num] {
7            v[0] = num
8        }
9
10        m[num] = true
11    }
12
13    for i := 1; i <= len(nums); i++ {
14        if !m[i] {
15            v[1] = i
16            break
17        }
18    }
19
20    return v
21}
``````