LeetCode1-Two Sum

本文探讨了在给定整数数组中寻找两个数使它们的和等于特定目标值的问题。通过对比两次循环和构建哈希表两种算法,分析了时间与空间复杂度,展示了如何从6780ms优化至48ms。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最优解思路二。

 

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.  

Example:  

Given nums = [2, 7, 11, 15], target = 9,  
Because nums[0] + nums[1] = 2 + 7 = 9,  
return [0, 1].  

 首先是题意 'assume that each input would have exactly one solution' ,理解为 array 只有一组正确解。  
 ‘you may not use the same element twice’,应该理解为返回的indices不可以重复。  

 第一种思路,两次循环:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)-1):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

Runtime: 6780ms !!!

分析:  
两次循环,时间复杂度 $O(n^{2})$ ,没有额外的空间复杂度。

第二种思路, 构建hashtable,将第二次循环($ O(n) $)变成hashtable的查找键值对$O(1)$);  
hashtable 的 key 和  value分别为 target-num 和 index of num

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashtable = {}
        for i,num in enumerate(nums):
            if num in hashtable:
                return [hashtable[num], i]
            else:
                hashtable[target-num] = i

Runtime:48ms (引起舒适~~)

又看到相同思想的另一种写法,运行时间更少

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashtable = {}
        for i,num in enumerate(nums):
            if target-num in hashtable:
                return [hashtable[target-num], i]
            else:
                hashtable[num] = i


分析:   
一次循环,时间复杂度$O(n)$, 构建了hashtable,有额外的$O(n)$空间复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值