zoukankan      html  css  js  c++  java
  • leetcode349 350 Intersection of Two Arrays & II

     1 """
     2 Intersection of Two Arrays
     3 Given two arrays, write a function to compute their intersection.
     4 Example 1:
     5 Input: nums1 = [1,2,2,1], nums2 = [2,2]
     6 Output: [2]
     7 Example 2:
     8 Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
     9 Output: [9,4]
    10 """
    11 """
    12 由于问题中的元素是唯一的,所以我们只关心元素的有无,
    13 那么我们可以使用set这个结构。
    14 首先将nums1的所有数据存入set中,查找nums2中的数据是否在这个set中,
    15 如果在的话,我们将这个元素存入一个list里面。
    16 """
    17 class Solution:
    18     def intersection(self, nums1, nums2):
    19         """
    20         :type nums1: List[int]
    21         :type nums2: List[int]
    22         :rtype: List[int]
    23         """
    24         nums1 = set(nums1)
    25         result = set()
    26         for i in nums2:
    27             if i in nums1:
    28                 result.add(i)
    29         return list(result)
    30 
    31 """
    32 Given two arrays, write a function to compute their intersection.
    33 Example 1:
    34 Input: nums1 = [1,2,2,1], nums2 = [2,2]
    35 Output: [2,2]
    36 Example 2:
    37 Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    38 Output: [4,9]
    39 """
    40 """
    41 发现在leetcode349这个问题的基础上,
    42 我们多加了记录元素个数的功能,我们可以使用dict实现它。
    43 """
    44 class Solution:
    45     def intersect(self, nums1, nums2):
    46         """
    47         :type nums1: List[int]
    48         :type nums2: List[int]
    49         :rtype: List[int]
    50         """
    51         record, result = {}, []
    52         for num in nums1:
    53             record[num] = record.get(num, 0) + 1
    54             # dict.get(key, default=None)返回指定键的值,如果值不在字典中返回默认值None
    55             #{1: 2, 2: 2}
    56         for num in nums2:
    57             if num in record and record[num]:
    58             # num in record 里而且 对应有重复值
    59                 result.append(num)
    60                 record[num] -= 1
    61         return result
  • 相关阅读:
    如何正确得到某个元素的位置
    jQuery Tags Input Plugin(添加/删除标签插件)
    [转载]舒迅:产品经理必读的九步法
    不间断循环滚动代码
    jquery validate api
    jquery文件上传控件 Uploadify
    关于CSS权重问题
    css中fontfamily的中文字体
    expression解决IE6下固定定位的兼容
    模拟下拉select
  • 原文地址:https://www.cnblogs.com/yawenw/p/12271072.html
Copyright © 2011-2022 走看看