算法题:一手顺子,把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。OC实现。

爱丽丝有一手(hand)由整数数组给定的牌。 

现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。

如果她可以完成分组就返回 true,否则返回 false。

来源:力扣(LeetCode)

暴力解法,用OC实现。

实现思路:

  1. 将每张牌的张数进行统计,并放入字典中;
  2. 对字典的key进行升序排序;
  3. 循环字典,拿字典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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Win_77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值