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非常大,我可以采取最低的键值对?
谢谢!
正如@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)
| 归档时间: |
|
| 查看次数: |
978 次 |
| 最近记录: |