【每日一题Day124】LC2347最好的扑克手牌 | 哈希表

该问题涉及利用哈希表计算给定扑克牌中相同花色和相同大小的牌的数量。通过对每张牌的处理,找到最大花色匹配数和最大大小匹配数,以判断最好的手牌类型,如Flush、ThreeofaKind、Pair或HighCard。算法的时间和空间复杂度均为线性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最好的扑克手牌【LC2347】

You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].

The following are the types of poker hands you can make from best to worst:

  1. "Flush": Five cards of the same suit.
  2. "Three of a Kind": Three cards of the same rank.
  3. "Pair": Two cards of the same rank.
  4. "High Card": Any single card.

Return a string representing the best type of poker hand you can make with the given cards.

Note that the return values are case-sensitive.

  • 思路:使用哈希表记录花色相同的扑克牌的数量以及大小相同的扑克牌的数量,并使用变量记录花色相同的最大数量和大小相同的最大数量,最后从好到坏返回手牌类型

  • 实现

    class Solution {
        public String bestHand(int[] ranks, char[] suits) {
            int n = ranks.length;
            Map<Integer,Integer> count = new HashMap<>();
            int maxSuit = 0, maxRank = 0;
            for (int i = 0; i < n; i++){
                int rank = ranks[i], suit = suits[i];
                count.put(rank, count.getOrDefault(rank, 0) + 1);
                count.put(suit, count.getOrDefault(suit, 0) + 1);
                maxSuit = Math.max(maxSuit, count.get(suit));
                maxRank = Math.max(maxRank, count.get(rank));
            }
            if (maxSuit == 5){
                return "Flush";
            }else if (maxRank >= 3){
                return "Three of a Kind";
            }else if (maxRank == 2){
                return "Pair";
            }
            return "High Card";
    
        }
    }
    
    • 复杂度
      • 时间复杂度: O ( n ) O(n) O(n)
      • 空间复杂度: O ( 1 ) O(1) O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值