zoukankan      html  css  js  c++  java
  • LC217 存在重复元素

    哈希大法好!

    直接上代码
     1 typedef struct HashTable {
     2     int *data;
     3     int *flag;
     4     int size;
     5 } HashTable;
     6 
     7 HashTable *init(int n) {
     8     HashTable *h = (HashTable *)malloc(sizeof(HashTable));
     9     h->data = (int *)malloc(sizeof(int) * n);
    10     h->flag = (int *)calloc(sizeof(int), (n / 31 + 1));
    11     h->size = n;
    12     return h;
    13 }
    14 
    15 int hash(int val) {
    16     return val & 0x7fffffff;
    17 }
    18 
    19 int check(HashTable *h, int ind) {
    20     int x = ind / 31, y = ind % 31;
    21     return h->flag[x] & (1 << y);
    22 }
    23 
    24 void set(HashTable *h, int ind, int val) {
    25     int x = ind / 31, y = ind % 31;
    26     h->flag[x] |= (1 << y);
    27     h->data[ind] = val;
    28     return ;
    29 }
    30 
    31 void insert(HashTable *h, int val) {
    32     int ind = hash(val) % h->size;
    33     int times = 1;
    34     while (check(h, ind)) {
    35         ind += (times * times);
    36         ind %= h->size;
    37     }
    38     set(h, ind, val);
    39     return ;
    40 }
    41 
    42 int query(HashTable *h, int val) {
    43     int ind = hash(val) % h->size;
    44     int times = 1;
    45     while (check(h, ind) && h->data[ind] != val) {
    46         ind += (times * times);
    47         ind %= h->size;
    48     }
    49     return check(h, ind);
    50 }
    51 
    52 void clear(HashTable *h) {
    53     if (h == NULL) return ;
    54     free(h->data);
    55     free(h->flag);
    56     free(h);
    57     return ;
    58 }
    59 
    60 bool containsDuplicate(int* nums, int numsSize){
    61     HashTable *h = init(numsSize * 3);
    62     for (int i = 0; i < numsSize; i++) {
    63         if (query(h, nums[i])) {
    64             clear(h);
    65             return true;
    66         }
    67         insert(h, nums[i]);
    68     }
    69     clear(h);
    70     return false;
    71 }
  • 相关阅读:
    HDU
    HDU
    POJ
    HDU
    HDU
    POJ
    HDU
    FZU
    LightOJ 1030 Discovering Gold 数学期望计算
    POJ 3061 Subsequence 二分查找
  • 原文地址:https://www.cnblogs.com/lihanwen/p/10981913.html
Copyright © 2011-2022 走看看