leetcode 1. Two Sum(两数之和)

解题方案

思路 1 ******- 时间复杂度: O(N^2)******- 空间复杂度: O(1)******

暴力解法,两轮遍历

beats 27.6%

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: 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]

思路 2 ******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

上面的思路1太慢了,我们可以牺牲空间换取时间

          2        7        11    15
         不存在   存在之中
lookup   {2:0}    [0,1]
  • 建立字典 lookup 存放第一个数字,并存放该数字的 index
  • 判断 lookup 种是否存在: target - 当前数字, 则表面 当前值和 lookup中的值加和为 target.
  • 如果存在,则返回: target - 当前数字 的 index 和 当前值的 index

beats 100%

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

来源:https://github.com/apachecn/awesome-algorithm/tree/master/docs/Leetcode_Solutions/Python

备注:若有不懂,请添加群号812791932,有小哥哥,小姐姐的耐心解答幺

猜你喜欢

转载自blog.csdn.net/mixiaolemy/article/details/84503514
今日推荐