题目:
: 给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。
示例 1:
输入:nums = [1,2,3,1]
输出:true
示例 2:
输入:nums = [1,2,3,4]
输出:false
示例 3:
输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true
提示:
- 1 <= nums.length <= 1 0 5 10^{5} 105
- − 1 0 9 -10^9 −109 <= nums[i] <= 1 0 9 10^9 109
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/contains-duplicate
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
- 首先我看到这个题目,我就想到用两个for循环直接暴力解决,结果最后一个测试点没过直接超时了。
- 然后我就想两个for循环的时间复杂度时O( n 2 n^2 n2),我就想怎么才能减少查找一个元素的时间。然后我就想到了写一个哈希表。
- 但是我不晓得C语言有没有哈希相关的头文件,我就只有自己手写一个哈希表。
- 到后面我提交的时候发现如果直接找数组的最大最小值来创建一个哈希表,有些例子会超过最大内存。
- 最后我就自己写了一个哈希函数解决上面那个我问题。
代码
哈希函数
int fhash(int num)
{
return num%500+500;
}
哈希表
typedef struct Node
{
int num;
int cnt;
struct Node* next;
}*hash;
哈希表的初始化
for(int i=0;i<1000;i++)
{
table[i]=(hash)malloc(sizeof(struct Node));
table[i]->next=NULL;
}
完整代码
bool containsDuplicate(int* nums, int numsSize){
typedef struct Node
{
int num;
int cnt;
struct Node* next;
}*hash;
hash table[1000];
for(int i=0;i<1000;i++)
{
table[i]=(hash)malloc(sizeof(struct Node));
table[i]->next=NULL;
}
for(int i=0;i<numsSize;i++)
{
if(table[fhash(nums[i])]->next==NULL)
{
hash t=(hash)malloc(sizeof(struct Node));
t->num=nums[i];
t->cnt=1;
t->next=table[fhash(nums[i])]->next;
table[fhash(nums[i])]->next=t;
}
else
{
hash temp=table[fhash(nums[i])]->next;
while(temp!=NULL)
{
if(nums[i]==temp->num)
{
return true;
}
temp=temp->next;
}
hash t=(hash)malloc(sizeof(struct Node));
t->num=nums[i];
t->cnt=0;
t->next=table[fhash(nums[i])]->next;
table[fhash(nums[i])]->next=t;
}
}
return false;
}
int fhash(int num)
{
return num%500+500;
}
注释
- 上面解决哈希冲突是用的链地址法。
- 这是萌新第一次写题解,如果要有啥问题可以在下面评论区里面问,如果我能解答尽量解答。
- 如果有啥问题,也希望大佬们能指出来。