题解 | #扑克牌顺子#
扑克牌顺子
http://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4
思路1
借助桶结构,将牌全部放入桶中,判断连续的牌数加上0的牌数等于5一定是顺子,左右非零牌的牌中间的连续区间只要有五个元素就一定是顺子
class Solution { public: bool IsContinuous( vector<int> numbers ) { //使用桶 //A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K //A, 2, 3, 4, 5是顺子 vector<int> bucket(13, 0); int count_0 = 0; //0的个数 for (int i = 0; i < 5; ++i) { if (numbers[i] == 0) count_0++; else bucket[numbers[i] - 1] = numbers[i]; } int count = 0; //非0个数 int i = 0; while (bucket[i] == 0) i++; int left = i; //最左非0下标 for (i; i < 13; ++i) { //连续非0的个数 if (bucket[i] > 0) count++; else break; } int right = 0; //最右非0下标 for (right = 12; right > 0; --right) if (bucket[right] > 0) break; //[left, right]只要刚好是5,则一定是顺子;连续的牌数加上0的牌数等于5一定是顺子 if (count + count_0 == 5 || right - left + 1 == 5) return true; else return false; } }; /* [1,1,2,3,4] */
思路2
先对五张牌排序,只要非零的牌最大和最小的牌差等于4就一定是顺子; 0的牌个数与最大和最小的牌差等于5就一定是顺子
class Solution { public: bool IsContinuous(vector<int> numbers) { //利用set容器排序 set<int> se; char count_0 = 0; //非零个数 for (int i = 0; i < 5; ++i) if (!numbers[i]) count_0++; for (int i = 0; i < 5; ++i) if(numbers[i]) se.insert(numbers[i]); set<int>::iterator it = se.begin(); //只要非零的牌最大和最小的牌差等于4就一定是顺子; 0的牌个数与最大和最小的牌差等于5就一定是顺子 //非零牌只有一张的情况也在其中 if (*(se.rbegin()) - *it + 1 == 5 || count_0 + *(se.rbegin()) - *it + 1 == 5) return true; return false; } }; /* [1,1,2,3,4] */