- 1.题目描述:两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
- 2.解题答案
- (1)时间复杂度(O(n))
思路:采取一边插入哈希表一边寻找一边在已经插入的哈希表中寻找的方式,每次都拿着即将插入哈希表的数字然后在哈希表中找是否存在剩下的那个函数。有人可能会问,在循环里面查找的话时间复杂度不就变高了嘛,但是哈希表查找时间可以说是o(1)是常数(避免冲突的算法采用链地址可能不为o(1),但一般不用链地址来避免冲突),所以总的时间复杂度就为o(n),哈希表就是一种用空间换取时间的算法。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> hash;//由于unorder_map速度要比map快所以选择无序哈希表
for(int i=0; i < nums.size();++i)
{
int another = target - nums[i];
if(hash.count(another))
{
res = vector<int>({hash[another], i});
return res;
}
hash[nums[i]] = i;
}
return res;
}
};
(2)时间复杂度(O(n2))
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};
(3)C代码学习
typedef struct hash_node {
int id; /* we'll use this field as the key */
int index;
UT_hash_handle hh; /* makes this structure hashable */
} hash_node;
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
int *two_nums = (int *)malloc(sizeof(int)*2);
hash_node *hash_table = NULL, *hash_item1 = NULL, *hash_item2 = NULL;
for (int i = 0; i < numsSize; i++)
{
// 查找哈希表中是否存在满足和为target的另一个值,若存在直接返回
int other_id = target - *(nums+i);
HASH_FIND_INT(hash_table, &other_id, hash_item1);
if (hash_item1) {
two_nums[0] = hash_item1->index;
two_nums[1] = i;
*returnSize = 2;
return two_nums;
}
// 将本次遍历的值放入哈希表,value为数组下标,key为对应数值
hash_item2 = (hash_node *)malloc(sizeof(hash_node));
hash_item2->id = *(nums+i);
hash_item2->index = i;
HASH_ADD_INT(hash_table, id, hash_item2);
}
return two_nums;
}