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) 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 排序
复杂度 On(logn) O n ( l o g n )
算法3 利用题目规则,只分配常量空间
复杂度 O(n) 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 位运算
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值