美文网首页
LeetCode:1.两数之和

LeetCode:1.两数之和

作者: 御坂10241 | 来源:发表于2020-05-02 23:49 被阅读0次
chaoxi.jpg

题目:

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

示例:

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

题解:

1.暴力破解brute force

# 思路1:brute force, 强搞!!!
#     使用两个for循环嵌套,注意不能使用相同的index
#     时间:O(n^2)  空间:O(1)
from typing import List

class Solution(object):
  def twoSum(self, nums:List[int], target:int) -> List[int]:
    for i in range(len(nums)):
      for j in range(i+1, len(nums)):
        if nums[i]+nums[j] == target:
          return [i, j]
    return None
    
s1 = Solution()
s1.twoSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 10)

执行结果:通过

显示详情

执行用时 :7680 ms, 在所有 Python3 提交中击败了5.03%的用户

内存消耗 :14.3 MB, 在所有 Python3 提交中击败了21.95%的用户

2.cache存储

# 思路2:cache存储
#     用cache存储需要找寻的值,因为我们需要返回index索引
#     时间:O(n)  空间:O(n)
from typing import List

class Solution(object):
    def twoSum(self, nums:List[int], target:int) -> List[int]:
        cache = dict()
        for idx, num in enumerate(nums):
            cur = target-num
            if num in cache:
                return [cache[num], idx]
            cache[cur] = idx
        return None

s1 = Solution()
s1.twoSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 10)

执行结果:通过
显示详情
执行用时 :64 ms, 在所有 Python3 提交中击败了54.08%的用户
内存消耗 :15.1 MB, 在所有 Python3 提交中击败了5.48%的用户

        # 另一种写法
        # cache = dict()
        # for idx, num in enumerate(nums):
        #     if num in cache:
        #         return [cache[num], idx]
        #     else:
        #         cache[target-num] = idx

执行结果:通过
显示详情
执行用时 :40 ms, 在所有 Python3 提交中击败了90.03%的用户
内存消耗 :15.2 MB, 在所有 Python3 提交中击败了5.48%的用户

相关文章

  • 【LeetCode通关全记录】1. 两数之和

    【LeetCode通关全记录】1. 两数之和 题目地址:1. 两数之和[https://leetcode-cn.c...

  • LeetCode(1. 两数之和)

    算法描述 : 算法实现 : Java实现 : Python实现

  • leetcode 1. 两数之和

    leetcode 1. 两数之和题目: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每...

  • 1.两数之和 LeetCode

  • [LeetCode] 1. 两数之和

    给定一个整数数列,找出其中和为特定值的那两个数。 你可以假设每个输入都只会有一种答案,同样的元素不能被重用。示例:...

  • LeetCode 1. 两数之和

    题目链接:https://leetcode-cn.com/problems/two-sum/description...

  • LeetCode 1. 两数之和

    题目描述 题解 暴力法 时间复杂度为,空间复杂度为。 哈希表法 时间复杂度为,空间复杂度为。 哈希表法进阶 时间复...

  • [LeetCode] 1. 两数之和

    前言 从今天开始,将会开启我的 LeetCode 打卡之路。为了能让打卡坚持下去,就给自己设定了用博客来记录打卡过...

  • LeetCode 1. 两数之和

    题目: 题目地址:https://leetcode-cn.com/problems/two-sum/ 问题描述: ...

  • Leetcode 1.两数之和

    题:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他...

网友评论

      本文标题:LeetCode:1.两数之和

      本文链接:https://www.haomeiwen.com/subject/mocrghtx.html