★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pgspgxcd-gu.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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]
Example 2:數組
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note:微信
給定兩個數組,編寫一個函數來計算它們的交集。app
示例 1:函數
輸入: nums1 = [1,2,2,1], nums2 = [2,2] 輸出: [2]
示例 2:spa
輸入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 輸出: [9,4]
說明:code
12mshtm
1 class Solution { 2 func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 var pool: [Int: Int] = [:] 4 for num in nums1 { 5 pool[num] = 1 6 } 7 8 var result: [Int] = [] 9 for num in nums2 { 10 if pool[num] != nil { 11 pool[num] = nil 12 result.append(num) 13 } 14 } 15 16 return result 17 } 18 }
16ms
1 class Solution { 2 func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 if nums1.count == 0 || nums2.count == 0 { 4 return []; 5 } 6 7 var intersectionDic:[Int:Bool] = Dictionary(); 8 9 for number in nums1 { 10 intersectionDic[number] = true 11 } 12 13 var intersectionArray:[Int] = Array(); 14 for number in nums2 { 15 let hasIntersection = intersectionDic[number] ?? false 16 guard hasIntersection else {continue} 17 18 intersectionArray.append(number) 19 intersectionDic[number] = false 20 } 21 22 return intersectionArray; 23 } 24 }
1 class Solution { 2 func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 //利用Set的基本集合操做 4 var set1:Set<Int> = Set(nums1) 5 var set2:Set<Int> = Set(nums2) 6 var res:Set<Int> = set1.intersection(set2) 7 //Set轉Array 8 return Array(res) 9 } 10 }
1 class Solution { 2 func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 let intersect = Set(nums1).intersection(Set(nums2)) 4 return Array(intersect) 5 } 6 }
20ms
1 class Solution { 2 func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 var sortedNums1 = nums1.sorted() 4 var sortedNums2 = nums2.sorted() 5 var ret: Set<Int> = [] 6 var i = 0 7 var j = 0 8 9 while i < sortedNums1.count && j < sortedNums2.count { 10 if sortedNums1[i] > sortedNums2[j] { 11 j+=1 12 } else if sortedNums1[i] < sortedNums2[j] { 13 i+=1 14 } else { 15 ret.insert(sortedNums1[i]) 16 i+=1 17 j+=1 18 } 19 } 20 21 return Array(ret) 22 } 23 }
24ms
1 class Solution { 2 func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 let s = Set<Int>.init(nums1) 4 var result = Set<Int>() 5 for value in nums2 { 6 if(s.contains(value) && !result.contains(value)){ 7 result.insert(value) 8 } 9 } 10 return Array<Int>.init(result) 11 } 12 }