题目连接:LeetCode - The World's Leading Online Programming Learning Platform
leetcode写C真的很多坑......
用 hash 拉链法 构造hash函数,才能写这么题小题。
cpp
typedef struct Node { // 得自己做个hash 拉链法
struct Node *next;
int val;
int sign;
}Node, * pNode;
void insert(int val, int sign, int hash, pNode nodeList[]) {
pNode newNode = (pNode) malloc(1 * sizeof(Node));
newNode->val = val;
newNode->sign = sign;
newNode->next=NULL; // leetCode的检测问题需要置空
//printf(" a");
if(nodeList[hash]) {
pNode node = nodeList[hash];
while(node->next) {
node = node->next;
}
node->next = newNode;
} else {
nodeList[hash] = newNode;
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize = 2; // leetCode需要指定返回多少数字
int *result = (int*)malloc(sizeof(int)*2); // leetCode避免内存被清空
int point1, point2, find = 0;
pNode nodeList[10000] = {0}; // 这里能写成动态分配内存就好了
// for(int i = 0; i < numsSize; i ++) printf("%d ", nums[i]);
for(int i = 0; i < numsSize; i ++) {
int val = target - nums[i];
int hash = abs(val % numsSize); // 做取余
//printf("%d ", hash);
if(nodeList[hash]) {
pNode nodeI = nodeList[hash];
//printf(" %d|%d ", nodeI->val, val);
while(nodeI) {
if((nodeI->val) == val) {
point1 = nodeI->sign;
point2 = i;
find = 1;
break;
}
nodeI = nodeI->next;
}
}
if(find) break;
insert(nums[i], i, abs(nums[i] % numsSize), nodeList);
}
result[0] = point1;
result[1] = point2;
//printf("\n%d %d", point1, point2);
return result;
}