zoukankan      html  css  js  c++  java
  • LeetCode 1 _ 两数之和

    1. 题目描述

    2. 代码

     1 class Solution:
     2     def twoSum(self, nums: 'List[int]', target: int) -> 'List[int]':
     3         s = {}
     4         for i in range(len(nums)):
     5             n = nums[i]
     6             cop = target - n
     7             if cop in s.keys():
     8                 return [s[cop],i]
     9             s[nums[i]] = i
    10         return  []

    思路: 遍历数组, 若target与当前值的差在字典s中, 则返回差值的索引和当前遍历的索引.

                              若target与当前值的差不在字典s中, 则把当前遍历数组的值和索引更新到字典s中.

    3. 语法整理

    3.1 字典

    1 d = {key1 : value1, key2 : value2 }

    3.2 访问字典的值: 把相应的键放入到方括号中

    1 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    2 print ("dict['Name']: ", dict['Name'])
    3 print ("dict['Age']: ", dict['Age'])
    1 dict['Name']:  Runoob
    2 dict['Age']:  7

    3.3 修改字典

    1 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    2  
    3 dict['Age'] = 8               # 更新 Age
    4 dict['School'] = "菜鸟教程"  # 添加信息

    3.4 字典keys()方法: 以列表返回一个字典所有的键.

    1 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    2 print(dict.keys()) 
    1 dict_keys(['Name', 'Age', 'Class'])

    补充自己写的一种方法,通过2个循环实现

    1 class Solution:
    2     def twoSum(self, nums: List[int], target: int) -> List[int]:
    3         n = len(nums)
    4         for i in range(n-1):
    5             for j in range(i+1,n):
    6                 if nums[i] + nums[j] == target:
    7                     return [i,j]
  • 相关阅读:
    蛋疼的时候写三消游戏(十一) 圆形时钟
    C# 中的volatile关键字 (我今天才知道)
    第十四周助教总结
    第十周助教总结
    第十二周助教总结
    C语言I博客作业04
    C语言I博客作业05
    C语言I博客作业02
    第十一周助教总结
    第十三周助教总结
  • 原文地址:https://www.cnblogs.com/vvzhang/p/13785991.html
Copyright © 2011-2022 走看看