剑指offer03:数组中重复的数组---leetcode:LCR 120. 寻找文件副本

设备中存有 n 个文件,文件 id 记于数组 documents。若文件 id 相同,则定义为该文件存在副本。请返回任一存在副本的文件 id

示例 1:

复制代码
输入:documents = [2, 5, 3, 0, 5, 0]
输出:0 或 5

提示:

  • 0 ≤ documents[i] ≤ n-1
  • 2 <= n <= 100000

思路,排序之后再看,原本以为是要返回重复的数组,打算用一个空数组做标记,结果只需返回一个重复的即可。

使用排序后的数组,找挨着的两个即可。排序的时间复杂度是O(nlogn),而找到重复元素的时间复杂度是O(n)。

cpp 复制代码
int compare(const void* a,const void* b){
    return *(int*)a-*(int*)b;
}
int findRepeatDocument(int* documents, int documentsSize) {
    qsort(documents,documentsSize,sizeof(int),compare);
    for(int i=0;i<documentsSize-1;i++){
        int j=1;
        if(documents[i]==documents[i+j]){
            return documents[i];
        }
    }
    return 0;
}

使用哈希,使用数组中的值作为下标,进行标记。防止数组中值溢出,使用取余的办法。

cpp 复制代码
int findRepeatDocument(int* documents, int documentsSize){
    int* hash=(int*)malloc(documentsSize*sizeof(int));
    for (int i = 0; i < documentsSize; i++) {
        hash[i] =-1;
    }
    for(int i = 0; i < documentsSize; i++){
        int p=documents[i]%documentsSize;
        if(hash[p]!=-1){
            return documents[i];
        }
        hash[documents[i]%documentsSize]=documents[i];
    }
    return 0;
}
相关推荐
Coovally AI模型快速验证21 小时前
当视觉语言模型接收到相互矛盾的信息时,它会相信哪个信号?
人工智能·深度学习·算法·机器学习·目标跟踪·语言模型
电院工程师1 天前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学
轮到我狗叫了1 天前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
丛雨要玩游戏1 天前
字符函数和字符串函数
c语言·开发语言·算法
八个程序员1 天前
自定义函数(C++)
开发语言·c++·算法
ad钙奶长高高1 天前
【C语言】初始C语言
c语言·开发语言·算法
罗西的思考1 天前
【Agent】 ACE(Agentic Context Engineering)源码阅读笔记---(3)关键创新
人工智能·算法
报错小能手1 天前
C++笔记(面向对象)静态联编和动态联编
开发语言·c++·算法
WBluuue1 天前
AtCoder Beginner Contest 430(ABCDEF)
c++·算法
小肖爱笑不爱笑1 天前
2025/11/5 IO流(字节流、字符流、字节缓冲流、字符缓冲流) 计算机存储规则(ASCII、GBK、Unicode)
java·开发语言·算法