题目: 给定两个数组,编写一个函数来计算它们的交集。
例子:
输入:nums1 = [1,2,3,4], nums2 = [2,2]
输出:[2]
输入:nums1 = [7,9,8], nums2 = [9,4,9,8,4,5,10]
输出:[9,8]
遍历法
1.先Set方法去重num1, 减少循环, let set1 = Set(nums1)
(Set和Array的区别在于,Set是无序的,且Set中不能存在重复的元素)
2.遍历set1, 如果num2包含 , result就插入
func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
let set1 = Set(nums1)
var result: [Int] = []
for i in set1 {
if nums2.contains(i){
result.append(i)
}
}
return result
}
Swift内置交集方法
intersection:
/// Returns a new set with the elements that are common to both this set and
/// the given sequence.
///
/// In the following example, the bothNeighborsAndEmployees
set is made up
/// of the elements that are in both the employees
and neighbors
sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
return Array(Set(nums1).intersection(Set(nums2)))
}
题目来源:力扣(LeetCode) 感谢力扣爸爸 :)
IOS 算法合集地址
网友评论