在大型NSDictionary中查找最低值和相应的键

das*_*ist 2 objective-c nsdictionary nsarray ios

我有一个NSDictionary NSString作为键和NSNumber值,如下所示

NSDictionary *dictionary = @{@"Apple" : [NSNumber numberWithInt: 6],
                             @"Banana" : [NSNumber numberWithInt: 1],
                             @"Peach" : [NSNumber numberWithInt: 14],
                             @"Lychee" : [NSNumber numberWithInt: 1]};
Run Code Online (Sandbox Code Playgroud)

在这里,我想找到最低的键和值,在这个例子中将是Lychee : 1和之间的关系Banana: 1.对于一个较小的字典,我只是按照这个答案的建议对所有值进行排序,并根据排名检索数组中的第一个(或绑定的)对象.但是,我想知道是否有办法做到这一点,如果NSDictionary非常,我可以采取最低的键值对?

谢谢!

Guy*_*gus 6

正如@Tommy所说,除了进行线性搜索之外别无选择.对字典进行排序将强加O(n log(n))的函数,而线性搜索显然是O(n).您需要使用以下内容:

NSDictionary *dictionary = @{@"Apple" : [NSNumber numberWithInt: 6],
                             @"Banana" : [NSNumber numberWithInt: 1],
                             @"Peach" : [NSNumber numberWithInt: 14],
                             @"Lychee" : [NSNumber numberWithInt: 1]};
NSString *lowestKey = nil;
int lowestValue = 0;
for (NSString *key in dictionary)
{
    int value = [dictionary[key] intValue];
    if (!lowestKey || value < lowestValue)
    {
        lowestKey = key;
        lowestValue = value;
    }
}
NSLog(@"Lowest: %@: %d", lowestKey, lowestValue);
Run Code Online (Sandbox Code Playgroud)

  • 对于那些不理解Guy所谓的"O(n log(n))"和"O(n)"的读者,算法的性能通常取决于输入元素的数量(n).一个非常好的排序算法必须进行n•log(n)比较.这写成`O(n log(n))`.线性通过n个元素的数组进行比较.这被称为"O(n)"表现.(操作次数直接与输入元素的数量相关.)请注意,真正的**BAD**排序算法可能会进行N ^ 2(n平方)比较.这写成'O(n ^ 2)`. (2认同)