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]
說明:排序
輸出結果中每一個元素出現的次數,應與元素在兩個數組中出現的次數一致。
咱們能夠不考慮輸出結果的順序。索引
# -*- 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