iphone - 用计数索引对数组进行排序

标签 iphone objective-c ios xcode nsarray

我有以下问题:我有一个整数数组,我想将它们放在一个数据结构中,该结构将使每个整数及其出现次数,然后按出现次数进行排序。

所以,如果我有:

[1, 3, 4, 6, 6, 3, 1, 3]

我会有:
[(4,1), (6,2), (1,2), (3,3)]

其中(x,y)==(整数,其出现的次数)。

我尝试使用NSCountedSet,但是效果不佳,我想知道这样做的最佳方法是什么。

到目前为止,我已经执行了以下操作:
NSCountedSet *totalSet = [[NSCountedSet alloc] initWithArray:finalArray];

其中finalArray是未排序完整原始数据的最终数组。 totalSet被分组为(x,y)但未排序(理想情况下,应按“y”排序)。

我也尝试这样做,但是没有用:
NSArray *sortedArray = [finalArray sortedArrayUsingSelector:@selector(compare:)];

然后执行:
NSCountedSet *totalSet = [[NSCountedSet alloc] initWithArray:finalArray];

但这并没有改变'totalSet'。

最佳答案

您可以将数字及其计数放入字典数组中,如下所示:

    NSArray *arr = @[@1, @3, @4, @6, @6, @3, @1, @3];
    NSCountedSet *totalSet = [NSCountedSet setWithArray:arr];
    NSMutableArray *dictArray = [NSMutableArray array];
    for (NSNumber *num in totalSet) {
        NSDictionary *dict = @{@"number":num, @"count":@([totalSet countForObject:num])};
        [dictArray addObject:dict];
    }
    NSArray *final = [dictArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES ]]];
    NSLog(@"%@",final);

关于iphone - 用计数索引对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872383/

相关文章:

android - 使用传出语音调用发送一次性密码(otp)

iphone - 以编程方式查找 iphone 内存时出现问题

iphone - 为什么标签在 TableView 中更改为重用单元格

iphone - 每个单元格中有多个项目的 UITableView

objective-c - cocoa 成分的透明流程创建

objective-c - 垂直对齐 UINavigationItems

objective-c - 释放属性(property)(Objective-C)

objective-c - 在文本容器插图中无法选择 NSTextView

iOS 十六进制加法

iphone - iOS初始化UIWebView清除导航历史记录