zoukankan      html  css  js  c++  java
  • Python [Leetcode 350]Intersection of Two Arrays II

    题目描述:

    Given two arrays, write a function to compute their intersection.

    Example:
    Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

    Note:

      • Each element in the result should appear as many times as it shows in both arrays.
      • The result can be in any order.

    解题思路:

    排序,对比

    代码如下:

    class Solution(object):
        def intersect(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            nums1.sort()
            nums2.sort()
            index_1 = 0
            index_2 = 0
            inter = []
    
            while index_1 < len(nums1) and index_2 < len(nums2):
                if nums1[index_1] == nums2[index_2]:
                    inter.append(nums1[index_1])
                    index_1 += 1
                    index_2 += 1
                elif nums1[index_1] < nums2[index_2]:
                    index_1 += 1
                else:
                    index_2 += 1
    
            return inter
    

      

  • 相关阅读:
    了解Boost神器
    官方教程避坑:编译ARM NN/Tensorflow Lite
    信号量 PV 操作
    MAC 读写 ntfs 格式的硬盘
    poj题目分类
    Gelfond 的恒等式
    那些scp里的烂梗
    b
    jmeter集合
    Jmeter文章索引贴
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5709537.html
Copyright © 2011-2022 走看看