---
# System prepended metadata

title: 645. Set Mismatch
tags: [Leetcode, python, array, c++, hash, easy]

---

###### tags: `Leetcode` `easy` `array` `hash` `python` `c++`

# 645. Set Mismatch

## [題目連結:] https://leetcode.com/problems/set-mismatch/description/

## 題目:
You have a set of integers ```s```, which originally contains all the numbers from ```1 to n```. Unfortunately, due to some error, one of the numbers in ```s``` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number.

You are given an integer array ```nums``` representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

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

## 解題想法:
* 題目為求，給一數組nums，長度len(nums)，表示要包含1~len(nums)的字母
    * 求數組中出現兩次的、與沒出現過的數字

* 額外紀錄一數組hasPos，長度=len(nums)，初始全為0，用以紀錄每個位置出現次數
    * for遍歷nums
    * 最後判斷hasPos.index(2)與hasPos.index(0)者即為res

## Python:
``` python=
class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n=len(nums)
        hashPos=[0 for _ in range(n)]
        for val in nums:
            hashPos[val-1]+=1
        return [hashPos.index(2)+1,hashPos.index(0)+1]
            
if __name__=='__main__':
    result=Solution()
    ans=result.findErrorNums(nums = [1,2,2,4])
    print(ans) #[2, 3]
```

## C++:
``` cpp=
#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        int n=nums.size();
        vector<int> res(2,0); //size=2,init=0
        vector<int> hashPos(n,0);
        for (auto val: nums){
            hashPos[val-1]+=1;
        }
        for (int i=0; i<n; i++){
            if (res[0]!=0 && res[1]!=0)
                break;
            else if (hashPos[i]==2)
                res[0]=i+1;
            else if (hashPos[i]==0)
                res[1]=i+1;
        }
        return res;
    }
};

int main(){
    vector<int> nums={1,2,2,4};
    Solution res;
    vector<int> ans=res.findErrorNums(nums);
    for (auto val:ans){
            cout<<val<<" ";
    }
    cout<<endl;
    return 0;
}

```