1. 两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
思路:
暴力枚举:第一眼看到这个题目的时候不难想到枚举。然后两层循环。
时间复杂度为O(n^2),这样的代价无疑是很大的。
哈希表:
我们遍历到数字 a 时,用 target 减去 a,就会得到 b,若 b 存在于哈希表中,我们就可以直接返回结果了。若 b 不存在,那么我们需要将 a 存入哈希表,好让后续遍历的数字使用。
但是这个表还不能使用数组类型的哈希表。因为不仅要使用对应的数值,还需要使用下标(最后需要返回)。在哈希表中插入和查找的时间复杂度通常是 O(1),因此整体的时间复杂度为 O(n)。C 语言本身没有提供内置的哈希表数据结构的,需要自己动手实现。实现向哈希表中插入键值对和通过键查找值的操作等。
C++是有std::unordered_map的。
暴力枚举:
/*** Note: The returned array must be malloced, assume caller calls free().*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {*returnSize = 2;int* returned = (int *)malloc(sizeof(int) * 2);for (int i = 0; i < numsSize; i++) {for (int j = i+1; j < numsSize; j++) {if ( i != j && nums[i] + nums[j] == target) {returned[0] = i;returned[1] = j;return returned;}}}*returnSize = 0;return NULL;
}
哈希表:
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;
}
这一期专栏记录将我每天的刷题,希望各位的监督,也希望和各位共勉。
追光的人,终会光芒万丈!!