首页 > 编程语言 > 详细

两个数组的交集 II

时间:2019-03-29 21:20:51      阅读:138      评论:0      收藏:0      [点我收藏+]

给定两个数组,编写一个函数来计算它们的交集。

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]

代码:

思路:

因为是要找相同的数,而且要求重复,可以考虑用一个带有索引的结构来作为中间过渡,这个时候用字典就非常好了

字典用法:https://blog.csdn.net/JNingWei/article/details/78757673

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        list =[]
        dict={}
        for num in nums1:
            if num not in dict:
                dict[num] = 1
            else:
                dict[num] +=1
        for num in nums2:
            if num in dict and dict[num] > 0 :
                dict[num] =dict[num] - 1
                list.append(num)
        return list

 

两个数组的交集 II

原文:https://www.cnblogs.com/guangluwutu/p/10623672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!