剑指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;
}
相关推荐
phltxy7 小时前
C语言操作符详解
java·c语言·算法
aqiu1111118 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考9 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾9 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研10 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183111 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974812 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye12 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展