LeetCode 350. Intersection of Two Arrays II

Description

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

Example 1:github

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:app

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

描述

給定兩個數組,編寫一個函數來計算它們的交集。ui

示例 1:指針

輸入: nums1 = [1,2,2,1], nums2 = [2,2]
輸出: [2,2]
示例 2:code

輸入: 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

源代碼文件在 這裏
©本文首發於 何睿的博客 ,歡迎轉載,轉載需保留 文章來源 ,做者信息和本聲明.

相關文章
相關標籤/搜索