題目: 給定兩個數(shù)組,編寫一個函數(shù)來計算它們的交集。
例子:
輸入: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, 減少循環(huán), let set1 = Set(nums1)
(Set和Array的區(qū)別在于应又,Set是無序的翅楼,且Set中不能存在重復(fù)的元素)
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內(nèi)置交集方法
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 算法合集地址