问题描述
如何在数组中查找重复元素?我有一系列电话号码,所以在电话号码中我应该从右侧开始向左侧搜索并找到类似的 6 个整数.那我应该把它们打印出来.
How to find Duplicate Elements in Array? I have array of phone numbers so in the phone numbers i should start searching from the right side to the left side and find similar 6 integers. then i should print them out.
推荐答案
要查找重复项,您可以通过电话号码建立交叉引用,然后将其过滤为仅重复项.例如,考虑:
To find duplicates, you could build cross reference by phone number, then filter that down to duplicates only. For example, consider:
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 中,您可以使用以下命令构建交叉引用字典:
In Swift 4, you can build the cross reference dictionary with:
let crossReference = Dictionary(grouping: contacts, by: { $0.phone })
或者,在 Swift 5.2 中(感谢 SE-0249),你可以这样做:
Or, in Swift 5.2 (thanks to SE-0249), you can do:
let crossReference = Dictionary(grouping: contacts, by: \.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
类型:
Clearly use whatever model types make sense for you, but the above uses the following Contact
type:
struct Contact {
let name: String
let phone: String
}
实现的方式有很多很多,所以我不会专注于上面的实现细节,而是专注于一个概念:通过某个键(例如电话号码)构建交叉引用原始数组然后过滤结果只是那些具有重复值的键.
There are many, many ways to implement this, so I wouldn't focus on the implementation details of the above, but rather focus on the concept: Build cross reference original array by some key (e.g. phone number) and then filter results down to just those keys with duplicate values.
听起来您想将这个反映重复项的结构展平为一个联系人数组(我不确定您为什么要这样做,因为您丢失了识别哪些是彼此重复项的结构)),但如果你想这样做,你可以flatMap
它:
It sounds like you want to flatten this structure that reflects the duplicates, into a single array of contacts (I'm not sure why you'd want to do that, as you lose the structure identifying which are duplicates of each other), but if you want to do that, you can flatMap
it:
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
对于 Swift 2 或 3 版本,请参阅此答案的先前版本.
For Swift 2 or 3 renditions, see previous renditions of this answer.
这篇关于使用 Swift 在数组中查找重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!