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:
"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.
Example 1:
Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"] Output: "Flush" Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".
Example 2:
Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"] Output: "Three of a Kind" Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind". Note that we could also make a "Pair" hand but "Three of a Kind" is a better hand. Also note that other cards could be used to make the "Three of a Kind" hand.
Example 3:
Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"] Output: "Pair" Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair". Note that we cannot make a "Flush" or a "Three of a Kind".
Constraints:
ranks.length == suits.length == 5
1 <= ranks[i] <= 13
'a' <= suits[i] <= 'd'
- No two cards have the same rank and suit.
最好的扑克手牌。
给你一个整数数组 ranks 和一个字符数组 suit 。你有 5 张扑克牌,第 i 张牌大小为 ranks[i] ,花色为 suits[i] 。
下述是从好到坏你可能持有的 手牌类型 :
"Flush":同花,五张相同花色的扑克牌。
"Three of a Kind":三条,有 3 张大小相同的扑克牌。
"Pair":对子,两张大小一样的扑克牌。
"High Card":高牌,五张大小互不相同的扑克牌。
请你返回一个字符串,表示给定的 5 张牌中,你能组成的 最好手牌类型 。注意:返回的字符串 大小写 需与题目描述相同。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-poker-hand
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 counting sort。
- 判断是不是同花,就是判断每张牌的花色是否跟第一张牌的花色一样,如果一样,即第一张牌花色的出现次数 == 牌的数量,则是同花
- 判断是不是三条和对子,则需要用 hashmap 记录每张数字不同的牌各自出现了几次,并且记录一个出现次数的最大值 max。如果 max >= 3,则说明有三条;如果 max == 2,则说明有对子
- 其余情况则只能是高牌
时间O(n)
空间O(n)
Java实现
class Solution { public String bestHand(int[] ranks, char[] suits) { int count = 0; char first = suits[0]; for (char suit : suits) { if (suit == first) { count++; } } if (count == 5) { return "Flush"; } HashMap<Integer, Integer> map = new HashMap<>(); int max = 0; for (int r : ranks) { map.put(r, map.getOrDefault(r, 0) + 1); max = Math.max(max, map.get(r)); } if (max >= 3) { return "Three of a Kind"; } else if (max == 2) { return "Pair"; } return "High Card"; } }
标签:2347,ranks,max,Three,suits,cards,Hand,LeetCode,Kind From: https://www.cnblogs.com/cnoodle/p/17137159.html