zoukankan      html  css  js  c++  java
  • 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中, 希望每天刷三道题,坚持住,如果有错误或者不妥的地方,欢迎大家留言

  • 相关阅读:
    [git]使用Idea创建一个git项目
    [git]分支管理策略
    Restful 风格
    [spring boot]idea中实现热部署的方法
    [jquery]JSON.parse()与JSON.stringify()
    [spring mvc]<mvc: annotation-driven />的作用
    [spring mvc][转]<mvc:default-servlet-handler/>的作用
    [mybatis]传值和返回结果
    [spring]@Resource和@Autowired区别对比
    html流程实现
  • 原文地址:https://www.cnblogs.com/NaLaEur/p/9160463.html
Copyright © 2011-2022 走看看