Task1:两数之和


```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = [i for i in range(len(nums))]
        nums_dict = dict(zip(nums, n))  # 创建字典
        for i in range(len(nums)):
            add = target - nums[i]
            if add in nums_dict and nums_dict[add] != i:   # 判断数字是否在字典里,且不是重复的数
                return [i, nums_dict[add]]
结果输出:![在这里插入图片描述](https://img-blog.csdnimg.cn/20200301205427362.png)
用空间换取了一定的速度。时间复杂度为O(n)。
发布了5 篇原创文章 · 获赞 0 · 访问量 111

猜你喜欢

转载自blog.csdn.net/weixin_43535441/article/details/104599891
今日推荐