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

Problem: 645. 错误的集合

文章目录

题目描述

思路

1.排序

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

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

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

4.由于nums中本该记录1-n,则若numsn - 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;
    }
};
相关推荐
vibecoding日记3 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21385 小时前
Verilog参数化游程编码RLE模块
算法
望易5 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络9 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法