1,题目要求
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.
也就是,对于一个n个元素的数组,正确的值是1-n。但是由于一些数据错误,导致有错误的数字和重复的数字。
需要注意的是,错误的数字和重复的数字可能是一个,也可能不是。比如:
[2,3,3,5,4,6],重复的数字是3,缺少的数字是1。
对于返回值,是一个向量,第一个元素是重复的数字,第二个元素是缺少的数字。
2,题目思路
最开始以为重复的数字就包括了错误的数字,只要找到重复的数字就行。但是题目并不是这样。
因此一个可行的常规解决办法就是构建哈希表,一次遍历,统计每个数字出现的次数。二次遍历hash,等于0的就是miss,等于2的就是dul。
3,程序源码
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int>hash (nums.size());
int dul,miss;
for(auto num : nums)
{
hash[num-1]++;
}
for(int i = 0;i<hash.size();i++)
{
if(hash[i] == 0)
miss = i+1;
if(hash[i] == 2)
dul = i+1;
}
return {dul, miss};//快速的向量返回,不用再定义一个数组了
}
};