question
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
my answer
使用图的邻接矩阵的思想
//解题思路:使用图的邻接矩阵存储模型
#define N 100 //size of hash table
typedef struct node{
int val;
struct node* next;
}node;
typedef struct myHash{
node* head;
node* tail;
}myHash;
bool containsDuplicate(int* nums, int numsSize){
myHash* hashTable= (myHash*)malloc(100*sizeof(myHash));
// initialize
for (int i=0; i<N; ++i)
{
hashTable[i].head = hashTable[i].tail = NULL;
}
int tmp=0;
for (int i=0; i<numsSize; ++i)
{
tmp = ((int)abs(nums[i]))%N;
if (!hashTable[tmp].head)//hash表中当前元素所指的位置为空
{
//printf("a %d %d %d\n",nums[i],tmp, i);
node* newNode = (node*)malloc(sizeof(node));
newNode->val = nums[i];
newNode->next = NULL;
hashTable[tmp].head = newNode;
hashTable[tmp].tail = newNode;
}else{
//printf("b %d %d %d \n",nums[i],tmp, i);
node* ptrNode = hashTable[tmp].head;
//遍历检查当前链表
while(ptrNode){
if(ptrNode->val == nums[i])
return true;
ptrNode = ptrNode->next;
}
// 尾插法
ptrNode = (node*)malloc(sizeof(node));
ptrNode->val = nums[i];
ptrNode->next = hashTable[tmp].head;
hashTable[tmp].head = ptrNode;
}
}
return false;
}
others’ answer
使用bitmap的思想
#include <stdlib.h>
#define BIT_PER_WORD 32
#define SHIFT 5 //2^5==32
#define MARK 0x1f
#define MAX_NUM 10000000
/**
* 算法思路:使用bitmap结构
* (i & MARK) <-> i mod MARK
*/
void clear(int* arr, int i){//将元素i所对应的位置零
arr[i>>SHIFT] &= ~(1 << (i & MARK));
}
int test(int* arr, int i){//是否已经被填充
return arr[i>>SHIFT] & (1 << (i & MARK));
}
void set(int* arr, int i){//将元素i所在的位置1
arr[i>>SHIFT] |= (1 << (i & MARK));
}
int containsDuplicate2(int* nums, int numsSize){
int* arr = (int*)malloc((MAX_NUM/BIT_PER_WORD+1)*sizeof(int));
for(int i=0; i<numsSize; ++i){
clear(arr, nums[i]);
}
for(int i=0; i<numsSize; ++i){
if(test(arr, nums[i]))
return true;
set(arr, nums[i]);
}
return false;
}