如何判断 NSArray 中有多少个唯一元素
我有一个 NSString 数组(实际上是一个可变数组),我想找出数组中有多少个唯一元素。
例如,假设数组由以下部分组成:
Orange, Lemon, Lemon, Orange, Lemon
那么只有两个唯一元素(Orange 和 Lemon)。这个数组:
Paul, Steve, John, Harry, Paul, John
..有四个独特的元素。
我如何找到这个号码?
I've got an array (actually a mutable array) of NSStrings, and I want to find out how many unique elements the are in the array.
For instance, say the array is made up of:
Orange, Lemon, Lemon, Orange, Lemon
Then there are just two unique elements (Orange and Lemon). And this array:
Paul, Steve, John, Harry, Paul, John
..has four unique unique elements.
How do I discover this number?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSSet
不能包含相同的对象,因此以下内容有效:NSSet
can't contain equal objects, so the following works:对数组进行线性扫描,然后将每个元素添加到 NSMutableSet 中。
最后统计 NSMutableSet 中元素的数量。 NSMutableSet 不允许添加重复元素。
这比对数组进行排序要快,然后每次发现新元素时都会进行线性扫描以递增变量。
编辑:JoostK 提供了 Objective-C 中的实现。
Do a linear scan of the array, and, for each element, add it to an NSMutableSet.
Finally count the number of elements in the NSMutableSet. The NSMutableSet will not allow adding a repeated element.
This is faster then sorting the array, and then doing a linear scan incrementing a variable each time you discover a new element.
EDIT: the implementation in Objective-C has been provided by JoostK.