★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tcdxatmd-gr.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,2]
Example 2:數組
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note:微信
Follow up:app
1 class Solution { 2 func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 //定義兩個指針 4 var cur1:Int = 0 5 var cur2:Int = 0 6 var res:[Int] = [Int]() 7 var arr1: Array<Int> = nums1 8 var arr2: Array<Int> = nums2 9 //排序 10 arr1.sort(){$0 < $1} 11 arr2.sort(){$0 < $1} 12 while(cur1 < arr1.count && cur2 < arr2.count) 13 { 14 var num1 = arr1[cur1] 15 var num2 = arr2[cur2] 16 if num1 == num2 17 { 18 res.append(num1) 19 cur1 += 1 20 cur2 += 1 21 } 22 else if num1 < num2 23 { 24 cur1 += 1 25 } 26 else 27 { 28 cur2 += 1 29 } 30 } 31 return res 32 } 33 }
12msui
1 class Solution { 2 func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 var frequency = Dictionary( nums1.map{ ($0, 1) }, uniquingKeysWith: +) 4 var results = [Int]() 5 for num in nums2 { 6 if let value = frequency[num], value > 0 { 7 frequency[num] = value - 1 8 results.append(num) 9 } 10 } 11 return results 12 } 13 }
16msspa
1 class Solution { 2 func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 var map: [Int: Int] = [:] 4 for num in nums1 { 5 if let count = map[num] { 6 map[num] = count + 1 7 } else { 8 map[num] = 1 9 } 10 } 11 12 var result: [Int] = [] 13 for num in nums2 { 14 if let count = map[num], count >= 1 { 15 result.append(num) 16 map[num] = count - 1 17 } 18 } 19 return result 20 } 21 }
20ms指針
1 class Solution { 2 func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 var nums1 = nums1.sorted(by: <) 4 var nums2 = nums2.sorted(by: <) 5 6 var i:Int = 0, j:Int = 0 7 8 var n1:Int = 0, n2:Int = 0 9 10 var results:[Int] = Array() 11 12 while i < nums1.count && j < nums2.count { 13 n1 = nums1[i] 14 n2 = nums2[j] 15 if n1 < n2 { 16 i += 1 17 }else if n1 > n2 { 18 j += 1 19 }else { 20 results.append(n1) 21 i += 1 22 j += 1 23 } 24 } 25 return results 26 } 27 }
20mscode
1 class Solution { 2 3 func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 4 var dic = [Int: Int]() 5 var result = [Int]() 6 for value in nums1{ 7 if dic[value] != nil { 8 dic[value]! += 1 9 }else{ 10 dic[value] = 1 11 } 12 } 13 for value in nums2 { 14 if dic[value] != nil && dic[value] != 0{ 15 result.append(value) 16 dic[value]! -= 1 17 } 18 } 19 return result 20 } 21 }