zoukankan      html  css  js  c++  java
  • 350. 两个数组的交集 II

     思路详见注释。

     1 class Solution(object):
     2     def intersect(self, nums1, nums2):
     3         """
     4         :type nums1: List[int]
     5         :type nums2: List[int]
     6         :rtype: List[int]
     7         """
     8         # 保证s1短
     9         if len(nums1) > len(nums2):
    10             nums1, nums2 = nums2, nums1
    11 
    12         # 返回值
    13         res = [int] * len(nums1)
    14         # res下标
    15         index = 0
    16 
    17         # 遍历s1
    18         i = 0
    19         while i < len(nums1):
    20             # 数字在s2中,不在res中,则添加到res中,下标加1,指针后移
    21             if nums1[i] in nums2 and nums1[i] not in res:
    22                 # 该数字分别在两个list中出现的次数,取较小者
    23                 num = min(nums1.count(nums1[i]), nums2.count(nums1[i]))
    24                 # 在res中重复加入num个该数字
    25                 for j in range(num):
    26                     res[index] = nums1[i]
    27                     index += 1
    28                 i += 1
    29             # 指针后移
    30             else:
    31                 i += 1
    32         return res[0:index]
    33 
    34 if __name__ == '__main__':
    35     solution = Solution()
    36     print(solution.intersect(nums1=[4, 9, 5], nums2=[9, 4, 9, 8, 4]))
    37     print(solution.intersect(nums1=[1, 2, 2, 1], nums2=[2, 2]))
  • 相关阅读:
    bzoj 1497: [NOI2006]最大获利
    bzoj 2733: [HNOI2012]永无乡
    [CF911G]Mass Change Queries
    [CF911F]Tree Destruction
    [CF911E]Stack Sorting
    [CF911D]Inversion Counting
    [CF911C]Three Garlands
    [CF911B]Two Cakes
    [CF911A]Nearest Minimums
    [POJ1201]Intervals
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12712627.html
Copyright © 2011-2022 走看看