劍指offer (44) 撲克牌的順子

來源:互聯網
上載者:User

標籤:style   class   blog   code   color   strong   

題目:從撲克牌中隨機抽取5張牌,判斷是不是一個順子,即這5張牌是不是連續的

2-10為數字本身,A為1,J為11,Q為12,K為13,大小王可以替換任一數字

 

題解分析:

step1. 首先大小王看作0,與其他數字都區分開

step2. 對這5張牌排序

step3. 統計5張牌中0的個數和 相鄰數字之間的空缺總數,因為 我們可以把0替換掉空缺所需的數

bool IsContinuous(std::vector<int>& num){    if (num.size() != 5) return false;    std::sort(num.begin(), num.end());    int zeroNum = std::count(num.begin(), num.end(), 0);    int gapNum = 0;    for (int i = 0; i < num.size() - 1; ++i) {        if (num.at(i) == 0) continue;      // 直接跳過0        if (num.at(i) == num.at(i + 1)) {  // 有對子            return false;        }        gapNum += (num.at(i + 1) - num.at(i) - 1);    }    if (gapNum <= zeroNum) {        return true;    } else {        return false;    }}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.