350. Intersection of Two Arrays II--LeetCode Record
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 {
func intersect(nums1: [Int], _ nums2: [Int]) -> [Int] {
if nums1.count == 0 || nums2.count == 0 {
return nums1.count == 0 ? nums1 : nums2
}
var numCount1:[Int:Int] = [:]
var numCount2:[Int:Int] = [:]
countNum(nums1, &numCount1)
countNum(nums2, &numCount2)
let interNums = [Int](Set<Int>(nums1).intersect(nums2))
var result:[Int] = []
for inter in interNums {
if numCount1[inter] != nil && numCount2[inter] != nil {
for i in 0..<min(numCount1[inter]!,numCount2[inter]!){
result.append(inter)
}
}
}
return result
}
func countNum(nums: [Int], inout _ numCount: [Int:Int]){
for num in nums {
if numCount[num] == nil {
numCount[num] = 1
}else {
numCount[num] = numCount[num]! + 1
}
}
}
}
相關文章
- leetcode 350. Intersection of Two Arrays IILeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- CodeForces 1417B Two Arrays
- LeetCode 4. Median of Two Sorted ArraysLeetCode
- LeetCode Median of Two Sorted Arrays(004)解法總結LeetCode
- [LeetCode] 1385. Find the Distance Value Between Two ArraysLeetCode
- CF 773 (Div. 1) D. Two Arrays 雙指標 容斥指標
- Arrays
- leetcode 4. Median of Two Sorted Arrays 尋找兩個正序陣列的中位數(困難)LeetCode陣列
- Arrays Basics
- 六,Arrays
- 懶載入之intersection observerServer
- CF1093E [Intersection of Permutations]
- halcon學習擴充系列—交集intersection的擴充運算元intersection_expand
- react-recordReact
- Arrays工具類
- Active Record Associations
- Arrays+Collections
- 【java】Arrays類Java
- screen-record
- coca after two months vs in two months
- Java泛型裡的Intersection TypeJava泛型
- Sorting arrays in NumPy by column
- ES6+ ---- record
- Daily record-SeptemberAI
- Learn and Record12
- Java中Arrays作用Java
- 18_Arrays類
- Camera List Record - 120
- Java Arrays.sort()Java
- 精讀《react-intersection-observer 原始碼》ReactServer原始碼
- 實戰 Java 16 值型別 Record - 2. Record 的基本用法Java型別
- Java容器工具類ArraysJava
- Travel Notes-Record mood
- JAVA基礎--Arrays類Java
- Homework record-Simple sorting
- Arrays.copyOf 函式函式