/**
现有数据:[{tagName: 'p'}, {tagName: 'div'}, {tagName: 'p'}, ....],
请统计出现次数 TOP 1 的 tagName。
*/
/**
*统计出现次数最多的tagName
*可能出现多个,所以返回值是个数组
*/
- (NSArray *)topCountWithArray:(NSArray *)array{
NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:array.count];
//1.[p:3]
for (NSDictionary *dic in array){
//1.先根据key取出value ,让value 作为新字典的key
NSString *str = dic[@"tagName"];
NSNumber *countValue = [newDic objectForKey:str];
//2.加1
[newDic setObject:@([countValue intValue]+1) forKey:str];
}
int max = 0;//最大的数值肯定是一个数,{}可能对应多个
for (NSNumber *value in [newDic allValues]) {
if (max < [value intValue]) {
max = [value intValue];
}
}
return [newDic allKeysForObject:@(max)];
}
调用
NSArray *array = @[@{@"tagName": @"p"}, @{@"tagName": @"div"}, @{@"tagName": @"p"}];
NSLog(@"%@",[self topCountWithArray:array]);
结果
(p)
网友评论