2347.最好的扑克手牌
链接:2347.最好的扑克手牌
难度:Easy
标签:数组、哈希表、计数
简介:请你返回一个字符串,表示给定的 5 张牌中,你能组成的 最好手牌类型 。
题解 1 - rust
- 编辑时间:2023-02-20
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn best_hand(ranks: Vec<i32>, suits: Vec<char>) -> String {
        use std::collections::HashMap;
        let mut m = HashMap::<i32, i32>::new();
        for v in suits {
            let v = v as i32;
            let item = m.entry(v).or_insert(0);
            *item += 1;
            if *item == 5 {
                return "Flush".to_string();
            }
        }
        m.clear();
        for v in ranks {
            let item = m.entry(v).or_insert(0);
            *item += 1;
            if *item >= 3 {
                return "Three of a Kind".to_string();
            }
        }
        for (_, v) in m {
            if v >= 2 {
                return "Pair".to_string();
            }
        }
        "High Card".to_string()
    }
}
题解 2 - python
- 编辑时间:2023-02-20
- 执行用时:44ms
- 内存消耗:15MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def bestHand(self, ranks: List[int], suits: List[str]) -> str:
        n = len(set(suits))
        if n == 1:
            return 'Flush'
        c = Counter(ranks)
        if len(c) == 5:
            return 'High Card'
        for _, v in c.items():
            if v >= 3:
                return 'Three of a Kind'
        return 'Pair'
题解 3 - cpp
- 编辑时间:2023-02-20
- 内存消耗:10MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    string bestHand(vector<int>& ranks, vector<char>& suits) {
        unordered_map<int, int> m;
        for (auto &v : suits) {
            m[v] += 1;
            if (m[v] == 5) return "Flush";
        }
        m.clear();
        for (auto &v : ranks) {
            m[v] += 1;
            if (m[v] >= 3) return "Three of a Kind";
        }
        for (auto &item : m) {
            if (item.second >= 2) return "Pair";
        }
        return "High Card";
    }
};