easy 两数之和 哈希表 枚举

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值