LeetCode第一题,两数之和

  1. 题目如下
    image.png
    image.png
  2. 思路及算法
    题目只让我们输出一个答案,所以我们只需依次遍历,得到答案便返回即可
    暴力破解法
    由给出的列表,我们依次对其进行迭代时,对于所得到的数num时,我们会思考target-num是否在列表中
    所以我们一般会对其进行双重循环,第一次先得到一个未知数num,第二次我们再对列表中该数后的数查找是
    否有target-num(num前的元素已和num匹配可以忽略),有则返回两数索引,无则返回空列表
    代码
python代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] == target - nums[j]:
                    return [i,j]
        return []
C++代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int length = nums.size();
        for(int i=0;i<length;i++){
            for(int j=i+1;j<length;j++){
                if(nums[i] == target - nums[j]){
                    return {i,j};
                }
            }
        }
        return {};
    }
};

时间复杂度:O(N^2)
情况最坏的时候每个数都要匹配,这种方法在数据量很大的时候会大大增加程序运行时间,故不推荐使用
为了提搞程序运行效率,我们需要对算法进行改善
哈希表法
哈希表我们将会在后面的数据结构与算法中提到
我们将所给数组的索引与数值存储至哈希表中,往后每迭代一次便在哈希表中寻找是否有与target-num相
等的数值,若有则将两数索引返回,若无则返回空

Python代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}
        for index,value in enumerate(nums):
            anotherValue = target - value
            if anotherValue in hashmap:
                return [hashmap[anotherValue],index]
            hashmap[value] = index
        return None
C++代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i) {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) {
                return {it->second, i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
};

注:该C++代码来自官方解法

时间复杂度:O(N)

在这里我们学会了python中内置的 enumerate() 函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
image.png
代码解释来自菜鸟教程

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值