首页 > 其他 > 详细

Leetcode 350. Intersection of Two Arrays II

时间:2021-04-02 17:10:58      阅读:12      评论:0      收藏:0      [点我收藏+]

Description: Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Link: 350. Intersection of Two Arrays II

Examples:

Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.

思路: 发现一样的元素就放回返回值的list中并在原list中删除, pop(指定位置), remove(指定元素), del(a[0]),指定位置,但不传入index.

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        if len(nums2) > len(nums1):
            nums1, nums2 = nums2, nums1  
        for i in nums1:
            if len(nums2) == 0:
                return res
            if i in nums2:
                res.append(i)
                nums2.remove(i)
        return res

日期: 2021-04-02  加油!

Leetcode 350. Intersection of Two Arrays II

原文:https://www.cnblogs.com/wangyuxia/p/14610344.html

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