• 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
  • 相关阅读:
    BT5启动SSH服务
    RIP路由协议的水平分割和触发更新
    FATFS Copy Files
    spi master vhd
    altera cpld spi master verilog
    SPI bus master for System09
    How To Set a Status Flag in One Clock Domain, Clear It in Another
    VHDL 整数 小数 分数 分频
    vhdl 状态机
    The DualModulus Divider in VHDL
  • 原文地址:https://www.cnblogs.com/vvzhang/p/13790347.html
Copyright © 2020-2023  润新知