<span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px; background-color: rgb(255, 255, 255);"> 之前一直在思考是就在当前目录下写,还是直接开个目录写,想了想,还是直接就在hdu下面写吧,反正都是算法。</span>
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
中文的意思,大概就是给出一个数组,和特别的数,返回一个数组,数组中包含有两个恰好等于这个特别的数的下标,返回为空,这里贴的代码主要是使用c语言来实现的,我也是看了别人的代码,使用一个node节点来保存key,和val,key是值,value是下标,所有这样看来的话,这个数组是没有重复的元素的,然后使用结构题HashMap结构,一个保存大小,一个保存node的指针。
代码如下,我相信大多数人应该都能看懂,里面有的内存分配的方法我觉得很好。这里并没有写main函数
typedef struct HashNode {
int key;
int val;
} HashNode;
typedef struct HashMap {
int size;
HashNode** storage;
} HashMap;
HashMap* hash_create(int size);
void hash_destroy(HashMap* hashMap);
void hash_set(HashMap* hashMap, int key, int value);
HashNode* hash_get(HashMap* hashMap, int key);
HashMap* hash_create(int size){
HashMap* hashMap = malloc(sizeof(HashMap));
hashMap->size = size;
hashMap->storage = calloc(size, sizeof(HashNode*));
return hashMap;
}
void hash_destroy(HashMap* hashMap) {
for(int i; i < hashMap->size; i++) {
HashNode *node;
if((node = hashMap->storage[i])) {
free(node);
}
}
free(hashMap->storage);
free(hashMap);
}
void hash_set(HashMap *hashMap, int key, int value) {
int hash = abs(key) % hashMap->size;
HashNode* node;
while ((node = hashMap->storage[hash])) {
if (hash < hashMap->size - 1) {
hash++;
} else {
hash = 0;
}
}
node = malloc(sizeof(HashNode));
node->key = key;
node->val = value;
hashMap->storage[hash] = node;
}
HashNode* hash_get(HashMap *hashMap, int key) {
int hash = abs(key) % hashMap->size;
HashNode* node;
while ((node = hashMap->storage[hash])) {
if (node->key == key) {
return node;
}
if (hash < hashMap->size - 1) {
hash++;
} else {
hash = 0;
}
}
return NULL;
}
int* twoSum(int* nums, int numsSize, int target) {
HashMap* hashMap;
HashNode* node;
int rest, i;
// make the hashMap 2x size of the numsSize
hashMap = hash_create(numsSize * 2);
for(i = 0; i < numsSize; i++) {
rest = target - nums[i];
node = hash_get(hashMap, rest);
if (node) {
int* result = malloc(sizeof(int)*2);
result[0] = node->val;
result[1] = i;
hash_destroy(hashMap);
return result;
} else {
hash_set(hashMap, nums[i], i);
}
}
return NULL;
}