如何判断 NSArray 中有多少个唯一元素

发布于 2024-09-09 07:02:17 字数 316 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

滥情空心 2024-09-16 07:02:17

NSSet 不能包含相同的对象,因此以下内容有效:

NSUInteger count = [[NSSet setWithArray:array] count];

NSSet can't contain equal objects, so the following works:

NSUInteger count = [[NSSet setWithArray:array] count];
2024-09-16 07:02:17

对数组进行线性扫描,然后将每个元素添加到 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.

浪漫人生路 2024-09-16 07:02:17
NSUInteger count = [[array valueForKeyPath:@"@distinctUnionOfObjects.self"] count];
NSUInteger count = [[array valueForKeyPath:@"@distinctUnionOfObjects.self"] count];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文