#define L 0x1fff
typedef struct hnode{
int key;
int index;
struct hnode *next;
} HNode;
void hash_init(HNode ***htb, int len){
int i;
*htb = (HNode **)malloc(sizeof(HNode*) * len);
for(i=0; i<len; i++){
(*htb)[i] = NULL;
}
}
void hash_exit(HNode **htb, int len){
int i, cnt=0;
HNode *node, *last;
for(i=0; i<len; i++){
node=(htb)[i];
if(node) cnt++;
while(node){
last = node;
node = node->next;
free(last);
}
}
printf("len = %d, cnt = %d\n", len,cnt);
}
long long ABS(long long x){
return x > 0 ? x : -x;
}
void hash_insert(HNode **hash_table, int key, int i){
long long k=key;
int index =abs((int)ABS(k) % L);
HNode *node = (HNode *)malloc(sizeof(HNode));
node->key = key;
node->index = i;
node->next = hash_table[index];
hash_table[index] = node;
}
HNode *hash_find(HNode **table, int key, int j, int K) {
long long k=key;
int index =abs((int)ABS(k) % L);
HNode *p = table[index];
while(p){
if(p->key == key && abs((p->index)-j) <=K){
break;
}
p = p->next;
}
return p;
}
/*
* 方法1:
* 遍历数组,添加进哈希表,哈希查询条件是否满足,假如哈希表查询时间复杂度为O(1),
* 则整个算法时间复杂度为O(N)。
* Notes:
* 1. 哈希查询时添加查询的条件,看是否满足返回条件;
*/
bool containsNearbyDuplicate_bak(int* arr, int len, int k){
HNode **table, *p;
int i, j;
bool ret = false;
hash_init(&table, L);
for(i=0; i<len; i++){
p = hash_find(table, arr[i], i, k);
if(!p){
hash_insert(table, arr[i], i);
}else{
if(abs(p->index - i) <= k){
ret = true;
break;
}
hash_insert(table, arr[i], i);
}
}
hash_exit(table, L);
return ret;
}
typedef struct no{
int val;
int index;
} Node;
int cmp(Node *a, Node *b){
if(a->val < b->val){
return -1;
}else if(a->val > b->val){
return 1;
}
return a->index - b->index;
}
/*
* 方法二:排序
* 1. 按照值,index的优先级对数组进行排序,使用原数组构造一个专用数组,保存val以及index;
* 2. 对所构造数组进行排序
* 3. 遍历所构造数组,值相同的元素,如果想让其离得最近,则在所构造数组中一定是相邻的两个元素;
* 4. 时间复杂度,快速排序的时间复杂度O(logN);
*/
bool containsNearbyDuplicate(int* arr, int len, int k){
int i, j;
if(!arr || !len) return false;
Node tb[len];
int index = 0;
for(i=0; i<len; i++){
tb[i].val = arr[i];
tb[i].index = i;
}
qsort(tb, len, sizeof(Node), cmp);
for(i=0; i<len; i++){
printf("val=%d, index=%d\n", tb[i].val, tb[i].index);
}
for(i=0; i<len-1; i++){
if(tb[i].val == tb[i+1].val && abs(tb[i].index - tb[i+1].index)<=k ){
return true;
}
}
return false;
}
leetcode-219. 存在重复元素 II-C语言
最新推荐文章于 2022-02-25 19:30:07 发布