最好的扑克手牌【LC2347】
You are given an integer array
ranks
and a character arraysuits
. You have5
cards where theith
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:
"Flush"
: Five cards of the same suit."Three of a Kind"
: Three cards of the same rank."Pair"
: Two cards of the same rank."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 ( 1 )