zoukankan      html  css  js  c++  java
  • LeetCode 448 _ 找到所有数组中消失的数字

    1. 题目描述

    2. 代码

     1 class Solution:
     2     def findDisappearedNumbers(self, nums: 'List[int]') -> 'List[int]':
     3         dic = {}
     4         maxvalue = len(nums)
     5         result = []        
     6         for n in nums:
     7             if n not in dic:
     8                 dic[n] = 1
     9             else:
    10                 dic[n] += 1
    11         for i in range(1,maxvalue+1):
    12             if i not in dic:
    13                 result.append(i)
    14         return result

    思路: 先遍历数组, 把数组元素和该元素出现的次数存入字典中. (6-10)

             根据range()生成顺序序列来遍历字典的键, 如果键不在字典中, 则说明是数组中消失的字, 所以把该值添加进result中.

    3. 语法整理

    3.1 字典 in 操作符用于判断键是否存在于字典中

     1 dict = {'Name': 'Runoob', 'Age': 7}
     2  
     3 # 检测键 Age 是否存在
     4 if  'Age' in dict:
     5     print("键 Age 存在")
     6 else :
     7     print("键 Age 不存在")
     8  
     9 # 检测键 Sex 是否存在
    10 if  'Sex' in dict:
    11     print("键 Sex 存在")
    12 else :
    13     print("键 Sex 不存在")
    14  
    15  
    16 # not in
    17  
    18 # 检测键 Age 是否存在
    19 if  'Age' not in dict:
    20     print("键 Age 不存在")
    21 else :
    22     print("键 Age 存在")
    1 键 Age 存在
    2 键 Sex 不存在
    3 键 Age 存在

    3.2 range(): 如果需要遍历数字序列, 可以使用内置range()函数, 它会生成数列.

    1 for i in range(5,9) :
    2     print(i)
    3  
    4     
    5 5
    6 6
    7 7
    8 8
  • 相关阅读:
    [AX2012 R3]在SSRS报表中使用QR二维码
    [AX2012 R3]关于Alerts
    [AX2012 R3]关于Named user license report
    [AX2012]Report data provider调试
    [AX2012]Claims user
    [AX2012]发送广播邮件
    [AX 2012] Woker user request
    AX2012 R3升级CU8的一些错误
    消失的银行 读后感
    Openstack实践(1)部署使用实例及neutron网络
  • 原文地址:https://www.cnblogs.com/vvzhang/p/13790347.html
Copyright © 2011-2022 走看看