LeetCode 1 - 两数之和

题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解法一:Python用字典

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dct = {}
        for i, n in enumerate(nums):
            if target - n in dct:
                return [dct[target - n], i]
            dct[n] = i

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

dict.get(key, default=None)

解法二:C++用哈希表

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hash;
        for(int i =0; i<nums.size(); i++)
        {
            if(hash.count(target-nums[i])) return {hash[target-nums[i]], i};
            hash[nums[i]] = i;
        }
        return {-1, -1};
    }
};

引用头文件(C++11):#include <unordered_map>
定义:unordered_map<int,int>、unordered_map<string, double>…
插入:例如将(“ABC” -> 5.45) 插入unordered_map<string, double> hash中,hash[“ABC”]=5.45
查询:hash[“ABC”]会返回5.45
判断key是否存在:hash.count(“ABC”) != 0 或 hash.find(“ABC”) != hash.end()

发布了55 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38204302/article/details/104313604