Set Mismatch问题及解法

来源:互联网 发布:ubuntu软件中心 编辑:程序博客网 时间:2024/06/04 23:34

问题描述:

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.

示例:

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

Note:

  1. The given array size will in the range [2, 10000].
  2. The given array's numbers won't have any order.
问题分析:

我们可以利用映射关系,记录每个数出现的次数,在n范围内,出现0次的就是缺失的数,出现两次的就是重复的数。


过程详见代码:

class Solution {public:    vector<int> findErrorNums(vector<int>& nums) {        vector<int> used(10001, 0);vector<int> res;for (int i = 0; i < nums.size(); i++){used[nums[i]]++;if (used[nums[i]] > 1){res.push_back(nums[i]);}}for (int i = 1; i <= nums.size(); i++){if (used[i] == 0){res.push_back(i);break;}}return res;    }};


原创粉丝点击