解题思路:
(1)若 handSize % groupSize != 0,直接返回false。
(2)若 groupSize = 1 ,直接return true。
(2)对数组hand进行排序,并且定义一个计数器count。
(3)这个题如果直接拿数组写的话,难点就在有重复数字上,若 hand[i] = hand[i+1],那么直接跳过此次循环。若 hand[i] = hand[i+1]-1 ,满足题意,count ++,将hand[i]赋值为-1,表示这个数已经被用过。
(4)当 count = groupSize 时,令 i = 0 ,重新开始循环。
注意:
(1)因为我们是拿 hand[i] 与 hand[i+1]做的比较,我们只需要比较groupSize 次就能选出一组牌,所以count要从1开始。
(2)当遇到 hand[i+1] = -1 时,交换 hand[i+1]与hand[i] 的值,然后在跳过此次循环。
(3)当判断hand[i] = hand[i+1]成立之后,需要注意判断hand[i+1]是不是最后一项,若是最后一项的话,说明就剩余两张相同的牌,return false。
代码:
int cmp_int(const void* x,const void* y)
{
return *(int*)x-*(int*)y;
}
void swap( int *x,int *y)
{
int tmp=*x;
*x=*y;
*y=tmp;
}
bool isNStraightHand(int* hand, int handSize, int groupSize)
{
if(handSize%groupSize != 0)
{
return false;
}
if(groupSize==1)
return true;
qsort(hand,handSize,sizeof(int),cmp_int);
int count=1;
for(int i=0;i<handSize-1;i++)
{
if(count==groupSize)
{
hand[i]=-1;
count=1;
i=0;
}
if(hand[i]==-1||hand[i]==hand[i+1])
{
if(i+1==handSize-1)
return false;
continue;
}
if(hand[i+1]==-1)
{
swap(&hand[i],&hand[i+1]);
continue;
}
if(hand[i]!=hand[i+1]-1)
return false;
hand[i]=-1;
count++;
}
return true;
}
如果这个题拿链表写的话,就不需要考虑这么多情况了。