645. Set Mismatch

406 篇文章 0 订阅
406 篇文章 0 订阅

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};//快速的向量返回,不用再定义一个数组了
        }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值