Leetcode_1
Leetcode 1
我的错误做法

这是我的做法,这是错的。在于输出结果这里,它是要输出指针型的整个数组,而这里我是直接输出数组元素。
错误原因:不知道怎么输出这个合适的类型
怎样输出指针型数组元素 尝试 return new int[]{i,j};
改正之后依然出现错误

这也是java的用法,不行!!
改正后

这个可以了。时间复杂度为O(n^2)
注意:
1.申请新的数组:
int * ret = malloc(sizeof(int) *2);
注意这个写法,c里面要手动申请空间,malloc这个数据类型的空间乘元素的个数
2.注意要把函数定义中的 returnSize也赋予值,完成所有任务
3.考虑找不到的情况,需要return NULL
null一定要是大写的,要写成NULL。同样的returnSize也需要赋予新的值
哈希表法 时间复杂度为O(n)
哈希表的基础知识

也就是说哈希表的访问速度极快,可以在O(1)的时间复杂度里找到哈希表中key为该值的元素
具体代码:
struct hashTable{
int key;
int val;
UT_hash_handle hh;
};
struct hashTable* hashtable;
struct hashTable* find(int ikey) {
struct hashTable* tmp;
HASH_FIND_INT(hashtable, &ikey, tmp);
return tmp;
}
void insert(int ikey, int ival) {
struct hashTable* it = find(ikey);
if(it == NULL) {
struct hashTable* tmp = malloc(sizeof(struct hashTable));
tmp->key = ikey, tmp->val = ival;
HASH_ADD_INT(hashtable, key, tmp);
}
else {
it->val = ival;
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
hashtable = NULL;
for(int i=0;i < numsSize; i++) {
struct hashTable* it = find(target - nums[i]);
if(it != NULL) {
int* ret = malloc(sizeof(int) *2);
ret[0] = it->val, ret[1] = i;
*returnSize = 2;
return ret;
}
insert(nums[i],i);
}
*returnSize = 0;
return NULL;
}

浙公网安备 33010602011771号