c++ 哈希表:
时间复杂度:
O
(
N
2
)
O(N^{2})
O(N2),其中 N 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。
空间复杂度:
O
(
1
)
O(1)
O(1)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//创建无序哈希表并重命名为 mp[key]=value ,此时 哈希表为空
unordered_map<int,int>mp ; // 创建无序哈希表并重命名为mp,key存的是nums中的值,value存的是下标
for(int i= 0;i<nums.size();i++){
int temp = target - nums[i]; // 要找的值
if(mp.count(temp)){ // 计数,如果在哈希表中
return {mp[temp],i}; //mp[key]= value,key放的是值,返回该值的下标(此时为空),和下标
}else{ // 如果不在哈希表中,存入哈希表
mp[nums[i]] = i; //nums[i]得到 mp的key,mp[key]=value 下标
}
}
return {-1,-1}; // 找不到
}
};
c 暴力枚举 :
时间复杂度:
O
(
N
)
O(N)
O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以
O
(
1
)
O(1)
O(1)地寻找 target - x。
空间复杂度:
O
(
N
)
O(N)
O(N),其中 N 是数组中的元素数量。主要为哈希表的开销。
/**
* Note: The returned array must be malloced, assume caller calls free().
int* returnSize 输出结果的个数
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){ // int* nums 是待搜索数组
int* ret = (int*)malloc(sizeof(int)*2); // 返回的数组(答案)
for(int i=0;i<numsSize-1;i++){
for(int j=i+1;j<numsSize;j++){
if(nums[i]+nums[j]==target){
// int* ret = (int*)malloc(sizeof(int)*2); // 返回的数组(答案)
ret[0] = i;
ret[1] = j;
*returnSize = 2; // 输出结果的个数
return ret;
}
}
}
*returnSize = 0;
return NULL;
}
python 暴力枚举:
时间复杂度:
O
(
N
)
O(N)
O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以
O
(
1
)
O(1)
O(1)地寻找 target - x。
空间复杂度:
O
(
N
)
O(N)
O(N),其中 N 是数组中的元素数量。主要为哈希表的开销。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_list = enumerate(nums)
for idx,n in nums_list:
if (target - n) in nums[idx+1:]:
# print(nums[idx+1:])
# print(nums[idx+1:].index(target-n)+idx+1)
return [idx,nums[idx+1:].index(target-n)+idx+1]
return None