力扣645. 错误的集合(排序,哈希表)

Problem: 645. 错误的集合

文章目录

题目描述

思路

1.排序

1.对nums数组按从小到大的顺序排序;

2.遍历数组时若判断两个相邻的元素则找到重复元素

3.记录一个整形变量prev一次置换当前位置元素并与其作差,若 等于2着说明缺失的数即为这中间的一个数(由于缺失的数可能是1,则初始化prev为0)

4.由于nums中本该记录1-n,则若nums[n - 1] != n,则说明缺失的数是n;

2.哈希表

1.对nums中的元素进行统计(以其大小为键,出现的次数为值);

2.从1-n开始遍历,若某一个值出现2次则为重复元素,若一个值没有出现(其值为0)则为缺失值

复杂度

思路1:

时间复杂度:

O ( n l o g n ) O(nlogn) O(nlogn);其中 n n n为数组nums的大小

空间复杂度:

O ( n ) O(n) O(n)

思路2 :

时间复杂度:

O ( n ) O(n) O(n)

空间复杂度:

O ( n ) O(n) O(n)

Code

思路1:

cpp 复制代码
class Solution {
public:
    /**
     * Sort
     * 
     * @param nums Given array
     * @return vector<int>
     */
    vector<int> findErrorNums(vector<int>& nums) {
        int n = nums.size();
        vector<int> res(2);
        sort(nums.begin(), nums.end());
        int prev = 0;
        for (int i = 0; i < n; ++i) {
            int curr = nums[i];
            if (curr == prev) {
                res[0] = prev;
            } else if (curr - prev > 1) {
                res[1] = prev + 1;
            }
            prev = curr;
        }
        if (nums[n - 1] != n) {
            res[1] = n;
        }
        return res;
    }
};

思路2:

cpp 复制代码
class Solution {
public:
    /**
     * Hash
     * 
     * @param nums Given array
     * @return vector<int>
     */
    vector<int> findErrorNums(vector<int>& nums) {
        vector<int> res(2);
        int n = nums.size();
        unordered_map<int, int> map;
        for (auto& num : nums) {
            map[num]++;
        }
        for (int i = 1; i <= n; ++i) {
            int count = map[i];
            if (count == 2) {
                res[0] = i;
            } else if (count == 0) {
                res[1] = i;
            }
        }
        return res;
    }
};
相关推荐
ZPC821011 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC821011 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David11 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱11 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone11 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩11 小时前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
蜡笔小马11 小时前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_5312371712 小时前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝12 小时前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Wect12 小时前
LeetCode 530. 二叉搜索树的最小绝对差:两种解法详解(迭代+递归)
前端·算法·typescript