URL
https://leetcode-cn.com/problems/hand-of-straights
题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/7f281e755c1646ca82c7ac2e97c89da9.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6L-H5b6X57K-5b2p,size_20,color_FFFFFF,t_70,g_se,x_16)
分析
![在这里插入图片描述](https://img-blog.csdnimg.cn/3d17a6d72b234961b4ad24f0403c0a8d.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6L-H5b6X57K-5b2p,size_20,color_FFFFFF,t_70,g_se,x_16)
源码
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
bool func(int *hand , int hand_size , int group_size);
static int cmp(const void * pa, const void * pb) {
return *(int *)pa - *(int *)pb;
}
typedef struct Node {
int val;
int freq;
} Node;
bool isNStraightHand(int* hand, int handSize, int groupSize) {
if (handSize % groupSize != 0) {
return false;
}
qsort(hand, handSize, sizeof(int), cmp);
Node * cnt = (Node *)malloc(sizeof(Node) * handSize);
memset(cnt, 0, sizeof(Node) * handSize);
int cardSize = 0;
for (int i = 0; i < handSize; ++i) {
if (i == 0) {
cnt[cardSize].val = hand[i];
cnt[cardSize].freq = 1;
} else {
if(hand[i] != cnt[cardSize].val) {
cardSize++;
}
cnt[cardSize].val = hand[i];
cnt[cardSize].freq++;
}
}
printf("\n");
for(int i = 0 ;i <cardSize ;i++){
printf("cnt[%d]=%d\n",cnt[i].val,cnt[i].freq);
}
int pos = 0;
for (int i = 0; i < handSize; ++i) {
while (pos < cardSize && cnt[pos].freq == 0) {
pos++;
}
if (cnt[pos].val == hand[i] && cnt[pos].freq > 0) {
printf("group = [ ");
for (int j = 0; j < groupSize; ++j) {
int num = hand[i] + j;
if (cnt[pos + j].freq > 0 && cnt[pos + j].val == num) {
cnt[pos + j].freq--;
printf("%d ",num);
} else {
return false;
}
}
printf("]\n");
}
}
free(cnt);
return true;
}
int main()
{
int hand[] = {1,2,3,6,2,3,4,7,8};
int hand_size = sizeof(hand)/sizeof(hand[0]);
int group_size = 3;
printf("ori : hand[] = ");
for (int i = 0 ;i <hand_size ;i++)
{
printf("%d,",hand[i]);
}
bool ret = false;
ret = isNStraightHand(hand , hand_size , group_size);
if(ret == true)
{
printf("true \n");
}else{
printf("false \n");
}
return 0;
}