LeetCode刷题记(一)--Python

272 阅读2分钟

1.Two Sum

Two Sum

难度: Easy

刷题内容 原题连接leetcode-twosum

内容描述

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].


简单翻译一下

1.两个总和 简单 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。

您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。

例:

被给NUMS = [2,7,11,15],目标变量TARGET = 9,

因为NUMS[0] + NUMS[1] = 2 + 7 = 9,

则返回[0,1]。

题意理解

  • 定义一个函数,接受两个参数,一个是给出的整数数组列表和一个被满足的目标变量,满足条件是从列表里找出两个相加等于目标变量值的整数,只返回这两个整数值的索引值组成的列表。

解题思路及方案

  • 暴力解法,两轮遍历

思路一:最直接想到的就是分别线性遍历一遍,不过时间复杂度: O(N^2)- 空间复杂度: O(1)******

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]

很显然上面对时间要求太多,可以牺牲空间换时间

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

  • 建立字典 lookup 存放第一个数字,并存放该数字的 index 判断 lookup 中是否存在: target
  • 当前数字, 则表面 当前值和 lookup中的值加和为 target. 如果存在,则返回: target
  • 当前数字 的 index 和 当前值的 index
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

执行说明

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):
            print("序号变量i :{i}  数值变量num :{num}".format(i=i,num=num))
            if target - num in lookup:
                print("返回找到的两个数的索引值列表:{}".format([lookup[target-num], i]))
            else:
                lookup[num] = i
                print("字典lookup:{}".format(lookup))

S = Solution()
nums = [2,7,13,11]
target = 9
S.twoSum(nums,target)

# 以下是 enumerate() 方法的语法:
#
# enumerate(sequence, [start=0])
# 参数
# sequence -- 一个序列、迭代器或其他支持迭代对象。
# start -- 下标起始位置。
# 返回值
# 返回 enumerate(枚举) 对象。
#
# 实例
# 以下展示了使用 enumerate() 方法的实例:
#
# >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
# >>> list(enumerate(seasons))
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
# >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

返回结果展示图

参考链接