我有一个NSDictionary,我想返回最接近零的对应键(包括负数的键):
NSDictionary *dict = @{
@"David" : @-89,
@"Bobby" : @61,
@"Nancy" : @-8,
@"Sarah" : @360,
@"Steve" : @203
};所以在这种情况下Nancy最接近..。我怎么能这么做?我搜了一遍,却空了出来。
发布于 2015-09-21 04:07:25
只需迭代这些值,并跟踪哪个值最接近于零。使用abs处理绝对值。
免责声明--下面的代码没有测试--可能是打字。它也假定整数。根据需要调整以支持浮点值。
NSDictionary *dict = ... // your dictionary
NSInteger closestValue = NSIntegerMax;
NSString *closestKey = nil;
for (NSString *key in [dict allKeys]) {
NSNumber *value = dict[key];
NSInteger number = (NSInteger)labs((long)[value integerValue]);
if (number < closestValue) {
closestValue = number;
closestKey = key;
}
}
NSLog(@"Closest key = %@", closestKey);发布于 2015-09-21 04:12:41
这是一个简单的最大最小问题,
NSString *curMinKey = [dict.allKeys firstObject];
NSInteger curMinVal = ABS([[dict objectForKey:curMinKey] integerValue]);
for(id key in dict) {
if(curMinVal > ABS([[dict objectForKey:key] integerValue])) {
curMinKey = key;
curMinVal = ABS([[dict objectForKey:key] integerValue]);
}
}
/// curMinKey is what you are looking forhttps://stackoverflow.com/questions/32687024
复制相似问题