• Python实现Leetcode------1. 两数之和


    1. 两数之和


    题目链接:点我


    思路

     有两种方式可以解决这个问题,一个是使用列表,一个是使用字典
    
    列表:
        思路:
            对列表中的所有元素进行遍历,先输入第一个元素A,然后判断nums中是否存在target - A
            若有的话将两个增加到列表中,注意,每次计算的时候应排除其背身
        所用函数
            1 添加元素   dirct.append()
            2 根据内容找到元素的序号  nums.index()
    
    字典:
        思路:
            判断目标元素是否在字典dirct中,如果在,就将其返回处理
            如果不在,将就数据加入dirct中,key为元素,元素值为其序列号
    

    代码演示

     1 nums = [3, 2, 4]
     2 target = 6
     3 
     4 class Solution:
     5 
     6     def twoSum_by_list(self, nums, target):
     7         """
     8         :type nums: List[int]
     9         :type target: int
    10         :rtype: List[int]
    11         """
    12         # 定义一个列表存放数据
    13         dirct = []
    14         for k, v in enumerate(nums):
    15             if target - v in nums:
    16                 if nums.index(target - v) != k:
    17                     dirct.append(k)
    18                     z = nums.index(target - v)
    19                     dirct.append(z)
    20                     return dirct
    21 
    22     def twoSum_by_dir(self, nums, target):
    23         dirc = {}
    24 
    25         for k, v in enumerate(nums):
    26             if target - v in dirc:
    27                 return [dirc.get(target - v), k]
    28             dirc[v] = k                
    29 
    30 
    31 if __name__ == '__main__':
    32     t1 = Solution()
    33     result = t1.twoSum_by_list(nums, target)
    34     print (result)
    35     result = t1.twoSum_by_dir(nums, target)
    36     print (result)
    View Code

    学习python中, 希望每天刷三道题,坚持住,如果有错误或者不妥的地方,欢迎大家留言

  • 相关阅读:
    Vue3使用vue3-video-player
    centos搭建phantomjs
    windows与Linux写入后门
    webService静态调用方法
    Web开发学习笔记(日更)
    docker修改容器绑定端口
    linux下~/.bashrc、/etc/profile、 $PATH环境变量 作用和修改
    docker for windows安装,修改images位置,修改镜像源,查看/var/lib/docker/containers
    hive修改表DDL
    python 高性能异步爬虫线程&线程池
  • 原文地址:https://www.cnblogs.com/NaLaEur/p/9160463.html
Copyright © 2020-2023  润新知