LeetCode刷题记(一)--Python

1.Two Sum

Two Sum

难度: Easygit

刷题内容 原题链接leetcode-twosumgithub

内容描述apache

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

Example:函数

Given nums = [2, 7, 11, 15], target = 9,ui

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].spa


简单翻译一下

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

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

例:

被给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')]
复制代码

返回结果展现图

参考连接

相关文章
相关标签/搜索