《剑指OFFER》刷题笔记 —— 扑克牌顺子
LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。
ERROR: VS 的错误提示 —— int (Solution::*) (const void* a, const void* b) 类型的实参与 int (_cdecl::*) (const void* , const void* ) 类型的形参不兼容****
class Solution {
public:
bool IsContinuous(vector<int> numbers) {
if (numbers.size() != 5)
return false;
//qsort(&numbers, numbers.size(), sizeof(int), compare);
qsort(&numbers[0], numbers.size(), sizeof(int), compare);
//sort(numbers.begin(), numbers.end());
int numZeros = 0;
int diff = 0;
for (int i = 0; i < numbers.size() - 1; ++i) {
if (numbers[i] == 0)
++ numZeros;
else {
if (numbers[i] == numbers[i + 1])
return false;
diff += numbers[i + 1] - numbers[i] - 1;
}
}
return (numZeros < diff) ? false : true;
}
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
};
CORRECT:
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
class Solution {
public:
bool IsContinuous(vector<int> numbers) {
if (numbers.size() != 5)
return false;
//qsort(&numbers, numbers.size(), sizeof(int), compare);
qsort(&numbers[0], numbers.size(), sizeof(int), compare);
//sort(numbers.begin(), numbers.end());
int numZeros = 0;
int diff = 0;
for (int i = 0; i < numbers.size() - 1; ++i) {
if (numbers[i] == 0)
++ numZeros;
else {
if (numbers[i] == numbers[i + 1])
return false;
diff += numbers[i + 1] - numbers[i] - 1;
}
}
return (numZeros < diff) ? false : true;
}
};
注意:
C++ 排序请使用 sort(),不要使用 C 语言中的 qsort();
转一下 https://stackoverflow.com/questions/12308243/trying-to-use-qsort-with-vector 的大佬评论:
First of all, DON'T.
If you just want to muck about, you can replace iterators with actual pointers:
qsort(&numbers[0], numbers.size(), sizeof(int), compvar);
Apart from not doing all the work std::sort
does, there is one unexpected thing about qsort
. It is slower.
sort (myvector1.begin(), myvector1.end());
sort (myvector2.begin(), myvector2.end(), myfunction);
sort (myvector3.begin(), myvector3.end(), myobject);
qsort(&myvector4[0], myvector4.size(), sizeof(int), cmyfunction);
4 is the slowest, followed by 2 (function pointer passed to std::sort
). 1 and 3 (default and functor) are the fastest (compiled with gnu's g++ with -O3 flag).