题目描述
从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王可以看成任意数字,认为大小王是0。
算法分析
首先把数组排序,再统计数组中0的个数,最后统计排序之后的数组中相邻数字之间的空缺总数。如果空缺的总数小于或者等于0的个数,那么这个数组就是连续的:反之则不连续。 最后,还需要注意,如果数组中的非0数字重复出现,则该数组不是连续的。
提交代码:
class Solution {
public:
bool IsContinuous(vector<int> numbers) {
if (numbers.empty())
return false;
QSort(numbers, 0, numbers.size() - 1);
int numOfZero = 0;
int numOfGap = 0;
// 统计数组中0的个数
for (int i = 0; i < numbers.size() && numbers[i] == 0; ++i)
++numOfZero;
int smallIndex = numOfZero;
int bigIndex = smallIndex + 1;
while (bigIndex < numbers.size())
{
if (numbers[smallIndex] == numbers[bigIndex])
return false;
numOfGap += numbers[bigIndex] - numbers[smallIndex] - 1;
smallIndex = bigIndex;
++bigIndex;
}
return numOfGap > numOfZero ? false : true;
}
void QSort(vector<int> &numbers, int beg, int end)
{
if (beg >= end)
return;
int pivot = Partition(numbers, beg, end);
QSort(numbers, beg, pivot - 1);
QSort(numbers, pivot + 1, end);
}
int Partition(vector<int> &numbers, int beg, int end)
{
int pivotkey = numbers[beg];
while (beg < end)
{
while (beg < end && pivotkey <= numbers[end])
--end;
swap(numbers[beg], numbers[end]);
while (beg < end && pivotkey >= numbers[beg])
++beg;
swap(numbers[beg], numbers[end]);
}
return beg;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, vector<int> &numbers, bool expected)
{
if (testName != nullptr)
printf("%s begins: ", testName);
Solution s;
if (s.IsContinuous(numbers) == expected)
printf("Passed.\n");
else
printf("Failed.\n");
}
void Test1()
{
vector<int> numbers = { 1, 3, 2, 5, 4 };
Test("Test1", numbers, true);
}
void Test2()
{
vector<int> numbers = { 1, 3, 2, 6, 4 };
Test("Test2", numbers, false);
}
void Test3()
{
vector<int> numbers = { 0, 3, 2, 6, 4 };
Test("Test3", numbers, true);
}
void Test4()
{
vector<int> numbers = { 0, 3, 1, 6, 4 };
Test("Test4", numbers, false);
}
void Test5()
{
vector<int> numbers = { 1, 3, 0, 5, 0 };
Test("Test5", numbers, true);
}
void Test6()
{
vector<int> numbers = { 1, 3, 0, 7, 0 };
Test("Test6", numbers, false);
}
void Test7()
{
vector<int> numbers = { 1, 0, 0, 5, 0 };
Test("Test7", numbers, true);
}
void Test8()
{
vector<int> numbers = { 1, 0, 0, 7, 0 };
Test("Test8", numbers, false);
}
void Test9()
{
vector<int> numbers = { 3, 0, 0, 0, 0 };
Test("Test9", numbers, true);
}
void Test10()
{
vector<int> numbers = { 0, 0, 0, 0, 0 };
Test("Test10", numbers, true);
}
// 有对子
void Test11()
{
vector<int> numbers = { 1, 0, 0, 1, 0 };
Test("Test11", numbers, false);
}
// 鲁棒性测试
void Test12()
{
Test("Test12", vector<int>(), false);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
Test11();
Test12();
return 0;
}