[东哥的leetcode刷题日记] leetcode 1 :Two Sum

leetcode 1 :Two Sum


题目链接: https://leetcode-cn.com/problems/two-sum/
难度: 简单
归类 : 数组操作,hashmap

题目

给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

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


解法

主要使用c++和python等两种语言进行了解答,以及经典题解和尝试改进的最优/最简洁解法。


个人解法

C++解法

//c++解法
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> hashmap;
        vector<int> res(2,0);
        for(int i = 0; i < nums.size(); i++){
            if(hashmap.find(target - nums[i]) != hashmap.end()){
                res[0] = hashmap[target - nums[i]];
                res[1] = i;
                return res;
            }else{
                hashmap[nums[i]] = i;
            }
        }
        return res;
    }
};

时间复杂度: O(N)
空间复杂度: O(N)
提交结果:
执行用时 :16 ms, 在所有 C++ 提交中击败了69.92%的用户
内存消耗 :8 MB, 在所有 C++ 提交中击败了100.00%的用户

python解法

#python解法
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        res = [0] * 2
        dict_hash = {}
        for i in range(len(nums)):
            if (target - nums[i]) in dict_hash:
                res[0] = dict_hash.get(target - nums[i])
                res[1] = i
                return res
            else:
                dict_hash.update({nums[i]: i})
        return res

时间复杂度: O(N)
空间复杂度: O(N)
提交结果:
执行用时 :64 ms, 在所有 Python3 提交中击败了60.83%的用户
内存消耗 :15.1 MB, 在所有 Python3 提交中击败了5.48%的用户


题解优解

此题有三种解法:
暴力法(O(N^2),O(1)),两遍哈希表(O(N),O(N)),一遍哈希表(O(N),O(N))

附上一个简洁的python版本。

#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

时间复杂度: O(N)
空间复杂度: O(N)
提交结果:
执行用时 :80 ms, 在所有 Python3 提交中击败了49.78%的用户
内存消耗 :15.1 MB, 在所有 Python3 提交中击败了5.48%的用户


尝试改进的最优解法

本题较为简单,无更优解法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值