在 Objective-C iPhone 中按数组中的众数排序
如果我有一个 NSArray,其中包含一些值。有没有一种方法使用描述符将其按数组中最常见的数字首先排序,最后按最不常见的数字排序,
Array has(
"3",
"2",
"1",
"3",
"3",
"7",
)
以
Array has(
"3",
"3",
"3",
"1",
"2",
"7",
)
If I have an NSArray with some values in them. Is there a way using descriptors to sort it by the most frequent number in the array first and the least frequent number at the end,
Array has(
"3",
"2",
"1",
"3",
"3",
"7",
)
to
Array has(
"3",
"3",
"3",
"1",
"2",
"7",
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
并非没有一些额外的数据结构。
所有 NSArray 排序操作(sortUsingDescriptors:、sortedArrayUsingSelector: 等)都假设您可以查看两个元素“a”和“b”并确定是否“a < b”,而无需查看 NSArray 中的任何其他元素。
一种解决方案是创建一个新数组,其成员对象同时包含值和频率计数(使用 NSDictionary 有效计算每个值有多少行)。例如:
然后很容易使用描述符按频率对该数组进行排序。
Not without some additional data structures.
All the NSArray sorting operations (sortUsingDescriptors:, sortedArrayUsingSelector:, etc.) assume that you can look at two elements "a" and "b" and determine if "a < b" without looking at any other elements in the NSArray.
One solution would be to create a new Array whose member objects contain both the value and the frequency count (use an NSDictionary to efficiently count how many rows there are for each value). For example:
Then it's easy to use a descriptor to sort that array by frequency.