加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
002_longest-consecutive-sequence.c 2.14 KB
一键复制 编辑 原始数据 按行查看 历史
xiashiwendao 提交于 2024-07-25 00:45 . 测试通过002
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "framework/hashtable/uthash.h"
struct hashTable
{
int key;
int val;
UT_hash_handle hh;
};
struct hashTable *my_ht;
static struct hashTable *hash_find(int ikey);
static void hash_insert(int ikey, int ival);
int longestConsecutive(int *nums, int numsSize);
static struct hashTable *hash_find(int ikey)
{
struct hashTable *tmp;
HASH_FIND_INT(my_ht, &ikey, tmp);
return tmp;
}
static void hash_insert(int ikey, int ival)
{
struct hashTable *it = hash_find(ikey);
if (it == NULL)
{
struct hashTable *tmp = malloc(sizeof(struct hashTable));
tmp->key = ikey;
tmp->val = ival;
HASH_ADD_INT(my_ht, key, tmp);
}
else
{
it->val = ival;
}
printf("insert str: %d, raw str: %d\n", ikey, ival);
}
int longestConsecutive(int *nums, int numsSize)
{
if (0 == numsSize)
{
return 0;
}
my_ht = NULL;
for (int i = 0; i < numsSize; i++)
{
int num = *(nums + i);
hash_insert(num, num);
}
int max_counter = 0;
struct hashTable *el, *tmp;
HASH_ITER(hh, my_ht, el, tmp)
{
printf("el->key: %d\n", el->key);
int num = el->key;
if (NULL == hash_find(num - 1))
{
printf("No head for: %d, so it is HEAD!\n", num);
int counter = 1;
while (hash_find(num + 1) != NULL)
{
counter++;
printf("find the next data: %d, the counter is: %d\n", num + 1, counter);
num++;
}
max_counter = max_counter > counter ? max_counter : counter;
}
else
{
printf("find the head for %d, so just skip!\n", num);
}
}
return max_counter;
}
void main(void)
{
// int nums[] = {100, 4, 200, 1, 3, 2};
// int nums[] = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};
int nums[] = {1, 2, 0, 1};
// int nums[] = {0};
int num_count = sizeof(nums) / sizeof(int);
printf("num_count: %d\n", num_count);
int max_counter = longestConsecutive(nums, num_count);
printf("max_count: %d\n", max_counter);
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化