LeetCode 0001 两数之和

题号0001 两数之和

题目地址 https://leetcode-cn.com/problems/two-sum


给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案 (这句话重点)

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

首先我自己会明确态度,知道自己有的写不到空间最优、时间最后等效果
秉着跟力扣以及各个大神学习算法思维,坚持首次独立思考+多次提交+尝试多语言版本

  1. 第一次提交:
    暴力法:最直接的方法就是两层循环,组合全部检测,直到找到退出
vector<int> twoSum(vector<int>& nums, int target)
 {
    vector<int> retIndex;
    for(auto i = 0; i < nums.size(); ++i)
    {
        for (auto j = i + 1; j < nums.size(); ++j)
        {
            if(nums[i] + nums[j] == target)
            {
                retIndex.push_back(i);
                retIndex.push_back(j);
                break;
            }
        }
    }

    return retIndex;
}

时间复杂度O(n^2),当然我知道这肯定不是最好的解决方法。查看LeetCode题解,寻找大神们的解释。使用hash_map来减少查询的时间,这样以空间换时间

2.二次提交
先使用std::map存储:一次循环将每个数的索引记录在一个map中,方便后面查找索引,第二次循环遍历,查找索引。

vector<int> twoSum2(vector<int>& nums, int target) {
    map<int, int> mapOtherIndex;
    for (auto i = 0;i < nums.size(); ++i) {
        mapOtherIndex[nums[i]] = i;
    }
    vector<int> retIndex;
    for(auto i = 0; i < nums.size(); ++i)
    {
        auto anotherVal = target - nums[i];
        if(mapOtherIndex.find(anotherVal) != mapOtherIndex.end()
                && i != mapOtherIndex[anotherVal])
        {
            retIndex.push_back(i);
            retIndex.push_back(mapOtherIndex[anotherVal]);
            break;
        }
    }

    return retIndex;
}

因为我是用的是std::map查找,平均时间复杂度(logn)。后面会使用hash_map将时间复杂度降低到O(1);

  1. 三次提交

题解还说明只需一次遍历就能完成。参考题解答案

一次遍历:个人理解为,边查找边插入,因为a+b = target,a和b是有相关性的,且a和b一定会出现在nums[]数组中。如果此次a,没有在map中找到,将它插入map中,那下次循环到b的时候,target - b一定会出现在map中,自然可以在map中找到,从而达到一次遍历的目的,完成更低的时间复杂度。

vector<int> twoSum3(vector<int>& nums, int target) {
    map<int, int> mapOtherIndex;
    vector<int> retIndex;
    for(auto i = 0; i < nums.size(); ++i)
    {
        auto anotherVal = target - nums[i];
        if(mapOtherIndex.find(anotherVal) != mapOtherIndex.end()
                && i != mapOtherIndex[anotherVal])
        {
            retIndex.push_back(mapOtherIndex[anotherVal]);
            retIndex.push_back(i);
            break;
        }

        mapOtherIndex.insert(std::map<int,int>::value_type(nums[i], i));
    }

    return retIndex;
}

Github地址:https://github.com/saberqueen/LeetingCodeExcise.git

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值