标签:class == 记录 fga deb str als min nal
题目描述
从扑克牌中随机抽取5张牌, 判断是不是一个顺子, 即这5张牌是不是连续的. 2~10为数字本身, A为1, J为11, Q为12, K为13, 大小王看成是任意数字并在数组中用0表示
class Solution {
public:
bool IsContinuous( vector<int> numbers ) {
if(numbers.size() != 5) return false;
int min = 14;
int max = -1;
int flag = 0;
for(int i = 0; i < numbers.size(); i++) {
int number = numbers[i];
if(number < 0 || number > 13) return false;
if(number == 0) continue;
if(((flag >> number) & 1) == 1) return false;
flag |= (1 << number);
if(number > max) max = number;
if(number < min) min = number;
if(max - min >= 5) return false;
}
return true;
}
};
class Solution {
public:
bool IsContinuous( vector<int> numbers ) {
if(numbers.empty()) {
return false;
}
vector<int> vt;
vt.resize(14);
int len = numbers.size();
int max = -1;
int min = 14;
for (int i = 0; i < len; i++) {
vt[numbers[i]]++;
if(0 == numbers[i]) {
continue;
}
if (vt[numbers[i]] > 1) {
return false;
}
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
if (max - min < 5) {
return true;
}
return false;
}
};
判断条件比下面那个简化多了, 使用一个变量记录排好序后数组相邻两个元素的差值
class Solution {
public:
bool IsContinuous( vector<int> numbers ) {
if (4 >= numbers.size()) {
return false;
}
sort(numbers.begin(), numbers.end());
int numbersOfZero = 0;
int numbersOfGape = 0;
int i = 0;
while (i < (numbers.size() - 1)) {
if (0 == numbers[i]) {
numbersOfZero++;
i++;
continue;
}
if (numbers[i] == numbers[i+1]) {
return false;
}
numbersOfGape = numbersOfGape + numbers[i+1] - numbers[i] - 1;
i++;
}
return (numbersOfGape > numbersOfZero ? false : true);
}
};
有点作弊了, 使用了排序函数, 最后的输出真是层层围堵, 各种判断
class Solution {
public:
bool IsContinuous( vector<int> numbers ) {
if (4 >= numbers.size()) {
return false;
}
sort(numbers.begin(), numbers.end());
int numberOfZero = 0;
int i = 0;
while (i < (numbers.size() - 1)) {
if (0 == numbers[i]) {
numberOfZero++;
i++;
continue;
}
if (numbers[i] == numbers[i+1]) {
return false;
}
else if (1 == numbers[i+1] - numbers[i]) {
i++;
}
else if ((numberOfZero > 0) && (numbers[i+1] - numbers[i] <= numberOfZero + 1)) {
numberOfZero = numberOfZero - (numbers[i+1] - numbers[i]) + 1;
i++;
}
else {
return false;
}
}
return true;
}
};
标签:class == 记录 fga deb str als min nal
原文地址:https://www.cnblogs.com/hesper/p/10527412.html