给定一个整数数组 nums 和一个整数目标值 target
在数组中找出和为目标值 target 的那两个整数, 并返回他们的数组下标
假设:
- 每种输入对应一个答案,
- 数组中同一个元素只能出现一次
/**
* 需要使用 hash 散列算法实现
* 散列函数: 除留余数法
* 冲突解决: 链表存储
*/
struct HashNode
{
unsigned char flag; // 0 未使用, 已使用
int key;
long val; //value -- index
struct HashNode *next;
};
/**
* 插入 HashNode
* @param node 节点数组 @param key 存储的 key @param val 存储的值 @param n 常量
**/
void insert_HashNode(struct HashNode * node, int key, long val, int n) {
int index = abs(key) % n;
struct HashNode * cnode = &node[index];
if(cnode->flag == 0) {
cnode->flag = 1;
cnode->val = val;
cnode->key = key;
return;
}
while(cnode->next != NULL) {
// cnode->next = cnode->next->next;
cnode = cnode->next;
}
cnode->next = (struct HashNode *) malloc(sizeof(struct HashNode));
cnode->next->val = val;
cnode->next->key = key;
}
/**
* 查找 HashNode
* @param node 节点数组 @param key 存储的 key @param n 常量
**/
int search_HashNode(struct HashNode * node, int key, int n){
int index = abs(key) % n;
struct HashNode * cnode = &node[index];
if(cnode->flag == 0) return -1;
do
{
if(cnode->key==key) {
return cnode->val;
}
cnode = cnode->next;
} while (NULL != cnode);
return -1;
}
/**
* 释放 HashNode 子节点 和 主节点
*/
void free_HashNode(struct HashNode * node, int n){
while(n > 0) {
struct HashNode * cnode = &node[--n];
if(cnode->flag == 1) {
cnode = cnode->next;
while (NULL != cnode)
{
void *point = cnode->next;
// printf("index: %d, node->key: %d, node->val: %d; node->next: %d ;
",n, cnode->key, cnode->val, cnode->next);
free(cnode);
cnode = point;
}
}
}
}
/***
* 打印测试 HashNode
* @param node HashNode @param n 常量
*/
void print_HashNode(struct HashNode *node, int n) {
for(int i = 0; i < n; i++) {
struct HashNode *cnode = &node[i];
printf("index: %d, node->key: %d, node->val: %d; node->next: %d ;
",i, cnode->key, cnode->val, cnode->next);
while(NULL != cnode->next) {
cnode = cnode->next;
printf("index: %d, node->key: %d, node->val: %d; node->next: %d ;
",i, cnode->key, cnode->val, cnode->next);
}
}
}
uint8 solution(int *indexs, int size, int * nums, int target) {
if(size < 2) return -1;
struct HashNode *node = (struct HashNode *)malloc(size * sizeof(struct HashNode));
//申请 大小为 size 的 node 数组
for(int i = 0; i < size; i++) {
int pindex = search_HashNode(node, target - nums[i], size);
if(-1 == pindex){
insert_HashNode(node, nums[i], i, size);
continue;
}
indexs[0] = pindex;
indexs[1] = i;
free_HashNode(node, size);
free(node);
return 1;
}
free_HashNode(node, size);
free(node);
return 0;
}
void test() {
int nums[] = { 2, 4, 1, 6, 8, 3, 9, 3 };
int target = 10;
int indexs[2] = { 0 };
if(solution(indexs, sizeof(nums)/sizeof(int), nums, target) == 1) {
printf("res:[%d, %d]
", indexs[0], indexs[1]);
}else {
printf("no res
");
}
}
void main() {
test();
}
//测试输出结果 res:[1, 3]