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
- 349. Intersection of Two Arrays--LeetCode RecordLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- LeetCode 350 [Intersection of Two Array II]LeetCode
- [leetCode][003] Intersection of Two Linked ListsLeetCode
- Leetcode-Intersection of Two Linked ListsLeetCode
- Swift-Median of Two Sorted ArraysSwift
- CodeForces 1417B Two Arrays
- Leetcode Median of Two Sorted ArraysLeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- 【Leetcode】160. Intersection of Two Linked ListsLeetCode
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- Leetcode-Median of Two Sorted ArraysLeetCode
- LeetCode 4. Median of Two Sorted ArraysLeetCode
- LeetCode2:Median of Two Sorted ArraysLeetCode
- 371. Sum of Two Integers--LeetCode RecordLeetCode
- LeetCode Median of Two Sorted Arrays(004)解法總結LeetCode
- 【LeetCode從零單排】No.160 Intersection of Two Linked ListsLeetCode
- CF 773 (Div. 1) D. Two Arrays 雙指標 容斥指標
- [LeetCode] Median of Two Sorted Arrays 兩個有序陣列的中位數LeetCode陣列
- Arrays
- delphi open arrays和dynamic arrays區別
- 六,Arrays
- 懶載入之intersection observerServer
- 【java】Arrays類Java
- Arrays工具類
- halcon學習擴充系列—交集intersection的擴充運算元intersection_expand
- leetcode 4. Median of Two Sorted Arrays 尋找兩個正序陣列的中位數(困難)LeetCode陣列
- Java泛型裡的Intersection TypeJava泛型
- coca after two months vs in two months
- Java中Arrays作用Java
- Java Arrays.sort()Java
- java Arrays陣列Java陣列
- 18_Arrays類
- react-recordReact
- 精讀《react-intersection-observer 原始碼》ReactServer原始碼
- Arrays.copyOf 函式函式
- Java容器工具類ArraysJava