如何在数组中查找重复元素?我有一组电话号码,因此在电话号码中,我应该从右侧到左侧开始搜索,并找到相似的6个整数。那我应该把它们打印出来。
要查找重复项,可以按电话号码建立交叉引用,然后将其过滤为仅重复项。例如,考虑:
let contacts = [ Contact(name: "Rob", phone: "555-1111"), Contact(name: "Richard", phone: "555-2222"), Contact(name: "Rachel", phone: "555-1111"), Contact(name: "Loren", phone: "555-2222"), Contact(name: "Mary", phone: "555-3333"), Contact(name: "Susie", phone: "555-2222") ]
在Swift 4中,您可以使用以下命令构建交叉引用字典:
let crossReference = Dictionary(grouping: contacts, by: { $0.phone })
要么
let crossReference = contacts.reduce(into: [String: [Contact]]()) { $0[$1.phone, default: []].append($1) }
然后,找到重复项:
let duplicates = crossReference .filter { $1.count > 1 } // filter down to only those with multiple contacts .sorted { $0.1.count > $1.1.count } // if you want, sort in descending order by number of duplicates
显然,请使用对您有意义的任何模型类型,但是上面的模型使用以下Contact类型:
Contact
struct Contact { let name: String let phone: String }
有很多方法可以实现此目的,因此我将不再关注上述实现细节,而是关注以下概念:通过某个键(例如电话号码)构建交叉引用原始数组,然后将结果过滤为那些具有重复值的键。
听起来您想将反映重复项的结构扁平化为单个联系人数组(我不确定为什么要这么做,因为您丢失了标识彼此重复的结构),但是如果您想这样做,可以flatMap:
flatMap
let flattenedDuplicates = crossReference .filter { $1.count > 1 } // filter down to only those with multiple contacts .flatMap { $0.1 } // flatten it down to just array of contacts that are duplicates of something else