标签:solution iostream art out sort pen 随机 include close
(1)首先应该对数组进行排序。
(2)统计数组中大小王(0)出现的个数。while(numbers[index]==0) ++index; // 统计0的个数
(3)统计数组中所有相邻数之间的间隔。
(4)同时还需要排除对子的情况,如果出现了对子,那么肯定不可能是顺子(0除外)。
(5)最后比较0的个数和间隔大小,如果0的个数大于等于间隔数,说明可以组成顺子。
1 class Solution { 2 public: 3 bool IsContinuous( vector<int> numbers ) { 4 if (numbers.size() != 5)return false; 5 6 sort(numbers.begin(), numbers.end()); 7 int numOfZero = 0; 8 //统计0的个数 9 for (int i = 0; i != 5; i++) { 10 if (!numbers[i]) 11 numOfZero++; 12 } 13 14 int beg = numOfZero+1; 15 int numOfGap = 0; 16 while (beg < 5) { 17 //如果出现了对子,那么肯定不可能是连子 18 if (numbers[beg - 1] == numbers[beg]) 19 return false; 20 21 numOfGap += numbers[beg] - numbers[beg - 1] -1; 22 beg++; 23 } 24 25 return (numOfZero >= numOfGap) ? true : false; 26 } 27 };
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 5 using namespace std; 6 7 int main() { 8 vector<int> data{ 5,7,6,0,4 }; 9 10 if (IsContinuous(data)) { 11 cout << "is continuous."<< endl; 12 } 13 else { 14 cout << "You don‘t get lucky." << endl; 15 } 16 17 system("pause"); 18 return 0; 19 } 20 21 bool IsContinuous(vector<int> numbers) { 22 if (numbers.size() != 5)return false; 23 24 sort(numbers.begin(), numbers.end()); 25 int numOfZero = 0; 26 //统计0的个数 27 for (int i = 0; i != 5; i++) { 28 if (!numbers[i]) 29 numOfZero++; 30 } 31 32 int beg = numOfZero+1; 33 int numOfGap = 0; 34 while (beg < 5) { 35 //如果出现了对子,那么肯定不可能是连子 36 if (numbers[beg - 1] == numbers[beg]) 37 return false; 38 39 numOfGap += numbers[beg] - numbers[beg - 1] -1; 40 beg++; 41 } 42 43 return (numOfZero >= numOfGap) ? true : false; 44 }
https://blog.csdn.net/m0_37950361/article/details/82153790
标签:solution iostream art out sort pen 随机 include close
原文地址:https://www.cnblogs.com/wxwhnu/p/11423271.html