爱丽丝有一手(hand)由整数数组给定的牌。
现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。
如果她可以完成分组就返回 true,否则返回 false。
来源:力扣(LeetCode)
暴力解法,用OC实现。
实现思路:
- 将每张牌的张数进行统计,并放入字典中;
- 对字典的key进行升序排序;
- 循环字典,拿字典key中的值,连续找w个数,如果找到了就在字典中把值减1,如果没找到就是不能组成顺子,返回NO。
-(BOOL)isNStraightHand:(NSArray *)hand and:(int)w
{
NSMutableDictionary *count = [NSMutableDictionary dictionary];
[hand enumerateObjectsUsingBlock:^(NSString *card, NSUInteger idx, BOOL * _Nonnull stop)
{
if (![count.allKeys containsObject:card])
{
count[card] = @"1";
}
else
{
count[card] = [NSString stringWithFormat:@"%d", [count[card] intValue] + 1];
}
}];
NSArray *keys = count.allKeys;
keys = [keys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2)
{
NSComparisonResult result = [obj1 compare:obj2];
return result == NSOrderedDescending;
}];
NSMutableArray *mutableKeys = [NSMutableArray arrayWithArray:keys];
while (count.count > 0)
{
int first = [mutableKeys[0] intValue];
for (int card = first; card < first + w; ++card)
{
if (![count.allKeys containsObject:[NSString stringWithFormat:@"%d", card]])
{
return NO;;
}
NSString *c = count[[NSString stringWithFormat:@"%d", card]];
if ([c intValue] == 1)
{
[count removeObjectForKey:[NSString stringWithFormat:@"%d", card]];
[mutableKeys removeObject:[NSString stringWithFormat:@"%d", card]];
}
else
{
count[[NSString stringWithFormat:@"%d", card]] = [NSString stringWithFormat:@"%d", [c intValue] - 1];
}
}
}
return YES;
}