• leetcode-001-Two sum


    一、问题描述

    二、解题思路

    这道题:exactly one solution,所以:1)不必考虑多解情况;2)不必考虑无解的异常处理。

    方法一:暴力搜索

    直接依次进行比较,时间复杂度O(n2):

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            for m,x in enumerate(nums[0:-1]):
                for n,y in enumerate(nums[(m+1):]):
                    res = (target-y)
                    if x == res:
                        return m,n+m+1
    

      用时过长:

     当然也可以先排序,再利用首/尾移动查找,复杂付O(n*logn)

    方法二:哈希表(O(n)

    class Solution(object):
        def twoSum(self, nums, target):
            buff_dict = {}
            for i in range(len(nums)):
                if nums[i] in buff_dict:
                    return [buff_dict[nums[i]], i]
                else:
                    buff_dict[target - nums[i]] = i
    

     

    class Solution(object):
        def twoSum(self,nums, target):
            dic = dict(((v, i) for i, v in enumerate(nums)))
            return next(( (i, dic.get(target-v)) 
                for i, v in enumerate(nums) 
                    if dic.get(target-v, i) != i), None)
    

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dic = {}
            for n,x in enumerate(nums):
                try:
                    return dic[x] , n
                except KeyError:
                    dic.setdefault(target - x,n)

    知识点

    • 在读取dict的key和value时,如果key不存在,就会触发KeyError错误
    • 利用next或者for进行遍历,迭代器对象从第一个元素开始访问,直到所有的元素被访问完结束,迭代器只前进不后退。
    • 生成字典:
      • dic = dict(((v, i) for i, v in enumerate(nums)))
      • dic.setdefault(target - x,n)
    • 位置1到末尾:enumerate(nums[0:-1]) 
  • 相关阅读:
    nginx.conf中配置laravel框架站点
    centos6.4下安装php7+nginx+mariadb环境
    Windows Terminal 安装和运行
    微软 WSL 重装操作系统
    Pulumi 如何在 Windows 环境中设置
    Ubuntu 20.04 安装 JDK
    代码的 Lint 是什么意思
    CentOS 8 手动安装 Go 1.16 版本
    Raspberry Pi 安装 go 后提示错误 Exec format error
    系统管理--查看网卡、内存等
  • 原文地址:https://www.cnblogs.com/xingshansi/p/6872816.html
Copyright © 2020-2023  润新知