Leetcode645 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:
The given array size will in the range [2, 10000].
The given array’s numbers won’t have any order.

思路

除了暴力求解之外,由于输入数组的size比较小,最容易想到的方法就是分配一个内存去记录,但更巧妙的方式还是利用规则本身。

算法1 分配内存记录

复杂度 O ( n )
(i)使用数组
class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        int map[10001];
        memset(map,0,10001*sizeof(int));
        int coverNum=0,coverdNum=0;
        for(int i=0;i<nums.size();i++)
        {
            if(map[nums[i]]==1)
                coverNum=nums[i];
            map[nums[i]]=1;
        }

        for(int i=1;i<=nums.size();i++)
        {
            if(map[i]==0)
            {
              coverdNum=i;
              break;
            } 
        }
        vector<int>result;
        result.push_back(coverNum);
        result.push_back(coverdNum);
        return result;
    }
};
(ii) 用HashMap

算法2 排序

复杂度 O n ( l o g n )

算法3 利用题目规则,只分配常量空间

复杂度 O ( n )

遍历nums数组,标记以nums[i]为下标的nums中的数。遍历到某数,以某数为下标的nums中的数已经被标记的话,该数就是重复的那个。
最后遍历数组,没有标记的那个位置就是缺失的数。

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {

        int dup=0,missing=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[abs(nums[i])-1]<0)
                dup=abs(nums[i]);
            else
                nums[abs(nums[i])-1]*=-1;           
        }

        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>0)
            {
              missing=i+1;
              break;
            } 
        }

        vector<int>result;
        result.push_back(dup);
        result.push_back(missing);
        return result;
    }
};

算法4 位运算

猜你喜欢

转载自blog.csdn.net/qq_24634505/article/details/80732614
今日推荐