在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [2,2]
Output: [2]
Example 2: Input: nums1 = [9,4,9,8,4]
Output: [9,4]
Note:
给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 说明:
12ms 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 }
|
请发表评论