Example #1
0
static
unsigned int voidP_hash(void *_x)
{
  size_t x = (size_t) _x;
  size_t hash = x;

#define DO_HASH(i) hash ^= ((hash << 15) | (hash >> 1)); hash ^= (x >> (i * 8)) & 0xff;
  switch ( sizeof(_x) ) {
  default:
    abort();
  case 8:
    DO_HASH(7);
  case 7:
    DO_HASH(6);
  case 6:
    DO_HASH(5);
  case 5:
    DO_HASH(4);
  case 4:
    DO_HASH(3);
  case 3:
    DO_HASH(2);
  case 2:
    DO_HASH(1);
  }
#undef DO_HASH

  return (unsigned int) hash;
}
Example #2
0
int* twoSum(int* nums, int numsSize, int target) {
#define HASH_LEN 4096
    int *result;
    do {
    	result = (int*)malloc(2 * sizeof(int));
    } while(!result);
    
    typedef struct NODE_ {
    	int value, idx;
    	struct NODE_ *next;
    } NODE;
    
    NODE *nodes;
    NODE *origin;
    do {
    	nodes = (NODE*)malloc(numsSize * sizeof(NODE));
    } while(!nodes);
    origin = nodes;
    NODE *table[HASH_LEN];
    int i;
    for (i = 0; i < HASH_LEN; ++i) table[i] = NULL;
    
    #define DO_HASH(value) ((int)(((unsigned int)value ^ (unsigned int)0xFF) + 1))
    for (i = 0; i < numsSize; ++i) {
    	int bucket = DO_HASH(nums[i]);
    	if (bucket < 0) bucket = -bucket;
    	bucket %= HASH_LEN;
    	
//    	printf("ADD: %d -> %d\n", nums[i], bucket);
    	NODE *new_node = nodes++;
    	new_node->idx = i;
    	new_node->next = table[bucket];
    	new_node->value = nums[i];
    	table[bucket] = new_node;
    }
    
    for (i = 0; i < numsSize; ++i) {
    	int rm = target - nums[i];
//    	printf("NUM: %d\n", nums[i]);
    	
    	int bucket = DO_HASH(rm);
    	if (bucket < 0) bucket = -bucket;
    	bucket %= HASH_LEN;
    	NODE *find = table[bucket];
    	while(find) {
    		if (find->value == rm && i != find->idx) {
    			result[0] = i;
    			result[1] = find->idx;
    			free(origin);
    			return result;
    		}
    		find = find->next;
    	}
//    	printf("NOT FOUND\n");
    	
    	
    	
    }
    free(origin);
    return NULL;
}