Leetcode-645 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:

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

上来很直接的思路就是:开一个数组做hash找重复值,然后利用等差数列求缺失值。时间O(N), 空间O(N)

// Space complexity O(n)
// Time complexity O(n)
class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        vector<int> res;
        int n = nums.size();
        int rep, mis;
        int hash[n + 1] = {0};
        for (int i = 0; i < n; i++){
            if (hash[nums[i]] == 0){
                hash[nums[i]] = 1;
            }
            else{
                rep = nums[i];
                break;
            }
        }
        int sum = accumulate(nums.begin(), nums.end(), 0);
        mis = (1 + n) * n / 2 - (sum - rep);
        res.push_back(rep);
        res.push_back(mis);
        return res;
    }
};

思路二:  不使用额外的空间的话,就要考虑数组值的特性了。这里的数字全为正。所以我们可以利用数字的正负做一个判断,判断有没有重复出现,以及有没有出现。要是只出现一次,那么对应位置的索引应该是负值,而如果出现两次,那么就不为负值了。

代码:

// Space complexity O(1)
// Time complexity O(n)
class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        vector<int> res;
        int n = nums.size();
        int rep, mis;
        for (int i = 0; i < n; i++){
            if (nums[ abs(nums[i]) - 1] > 0){
                nums[ abs(nums[i]) - 1] *= -1;
            }
            else{ 
                res.push_back(abs(nums[i]));
                
            }
        }
       for (int i = 0; i < n; i++){
           if (nums[i] > 0){
               res.push_back(i + 1);  // 丢失值对应的索引 - 1 就等于原来数组中没有变化的值(即大于0的值)
           }
       }
        
        
        return res;
    }
};
原文地址:https://www.cnblogs.com/simplepaul/p/7710996.html