美文网首页
TwoSum python求解

TwoSum python求解

作者: vckah | 来源:发表于2018-03-12 18:39 被阅读0次

leetcode 算法题,传送门
例子:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 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^2),于是在深思熟虑之后写下了只用一重循环的代码,用到了字典这一基本数据结构,仔细想想,如果只用判断 target - x == y 即可判断。仔细想想可以自己写出来。
但是我偶然在 stackoverflow 上遇到了一种更好的写法:

class Solution(object):
    def twoSum(self, nums, target):
        keys = {}
        for cnt, num in enumerate(nums):
            if target - num in keys:
                return keys[target-num], cnt
            keys[num] = cnt 

这里面用到了 enumerate ,我查了一下,这个内置函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。
它还提供了一个 start 参数,例如:


例子.png

嗯嗯,看来 enumerate 还是很方便的嘛!学些了!

相关文章

  • TwoSum python求解

    leetcode 算法题,传送门例子: 乍一看,没有经验的一定会用到两重循环,比如这样: 但是如果有经验的人就会思...

  • TwoSum

    刷题当然要从TwoSum开始了~~python刷题果然容易~~~class Solution(object):de...

  • 计算1到100的和

    利用递归求解 用 最笨的方法求解: 用python牛逼的sum求解: 用奇偶相加求解:

  • twoSum__Python3

    Given an array of integers, return indicesof the two numb...

  • 菜鸟刷 Leetcode成长笔记(持续更新中)

    第一题 TwoSum 如果对Python中的数据结构学习比较扎实的同学来说,python几行代码就可以搞定这道题的...

  • 1. leetcode python twosum

    最近再刷leetcode,用python 实现,贴出一些代码,希望指正. 问题描述:Given an array ...

  • LeetCode- twoSum-python

    Description Given an array of integers, return indices of...

  • 1两数之和2020-07-18

    Python 方法一:用 Python 中 list 的相关函数求解num2 = target - num1,是否...

  • python方程求解

    [Pythonによる科学・技術計算] 方程式の解を求める 解析解 sympy如果没有sympy,先安装:pip i...

  • TwoSum

    题目大意: 找到数组中两个元素相加等于指定数的所有组合 情况一:给定数组中不含重复元素,且均为正整数 思路: 使用...

网友评论

      本文标题:TwoSum python求解

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