LeetCode 350. Intersection of Two Arrays II

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

v2-48e14fa5c0e7ceced31c36662cd9f940_1440w.jpg

Description



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


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]


Note:

Each element in the result should appear as many times as it shows in both arrays.

The result can be in any order.


描述



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


示例 1:

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

输出: [2,2]


示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]

输出: [4,9]


说明:

输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。

我们可以不考虑输出结果的顺序。


思路


  • 对数组进行排序。
  • 对每个数组分别用一个指针 i,j,如果 i,j 指向的元素相等,则将这个元素放入到结果数组中,i, j 同时向后走一步。
  • 如果 i 所在的元素大,则 j 向后走一步。
  • 如果 j 所在的元素大,则 i 向后走一步。


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-04-09 16:31:05
# @Last Modified by:   何睿
# @Last Modified time: 2019-04-09 16:43:17
class Solution:
    def intersect(self, nums1: [int], nums2: [int]) -> [int]:
        nums1.sort(), nums2.sort()
        count1, count2 = len(nums1), len(nums2)
        i, j, res = 0, 0, []
        # 相同的部分一定在前面
        while i < count1 and j < count2:
            # 如果相等,添加到结果数组中
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i, j = i + 1, j + 1
            # 如果数组二的数大,将数组一的索引自增一次
            elif nums1[i] < nums2[j]:
                i += 1
            # 如果数组一的数大,将数组二的索引自增一次
            elif nums1[i] > nums2[j]:
                j += 1
        return res

源代码文件在 这里


目录
相关文章
|
6月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
16 0
|
存储 算法
LeetCode 350. 两个数组的交集 II ntersection of Two Arrays II
LeetCode 350. 两个数组的交集 II ntersection of Two Arrays II
|
Python
LeetCode 349. Intersection of Two Arrays
给定两个数组,编写一个函数来计算它们的交集。
51 0
LeetCode 349. Intersection of Two Arrays
Leetcode-Hard 4. Median of Two Sorted Arrays
Leetcode-Hard 4. Median of Two Sorted Arrays
77 0
|
人工智能
LeetCode之Intersection of Two Arrays
LeetCode之Intersection of Two Arrays
78 0
LeetCode 350: 两个数组的交集 II Intersection of Two Arrays II
题目: 给定两个数组,编写一个函数来计算它们的交集。 Given two arrays, write a function to compute their intersection. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [4,9] 说明: 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
697 0

热门文章

最新文章