【leetcode_846】【中等】hand-of-straights/ 一手顺子

文章目录

URL

https://leetcode-cn.com/problems/hand-of-straights

题目

在这里插入图片描述

分析

在这里插入图片描述

源码

/* 20211230 liam leecode 846 */

#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;
	}
	/* 1. quick sort */
	qsort(hand, handSize, sizeof(int), cmp);

	/* 2. hash list */
	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++;
		}
	}
	/* show hash list */
	printf("\n");
	for(int i = 0 ;i <cardSize ;i++){
		printf("cnt[%d]=%d\n",cnt[i].val,cnt[i].freq);
	}
	/* 3. Iterate hand[] */
	int pos = 0;
	for (int i = 0; i < handSize; ++i) {
		/* 3.1 Find the data in the HashList that exists in hand. */
		while (pos < cardSize && cnt[pos].freq == 0) {
			pos++;
		}
		/* 3.2 Skip the repeating elements in hand[]. 
		 * && The number of occurrences in a hashList is non-zero. */
		if (cnt[pos].val == hand[i] && cnt[pos].freq > 0) {
			/* 3.3 Match [CNT [pot].val, CNT [opt+j].val] 
			 * && Reduce cnt[opt+j].freq */
			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 if the data does not exist or the degree is 0. */
					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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

过得精彩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值