|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | + |
| 5 | +struct HashNode { |
| 6 | + int key; /* num[i] */ |
| 7 | + int value; /* i */ |
| 8 | + struct HashNode *next; |
| 9 | +}; |
| 10 | + |
| 11 | +static inline int hash(int key, int n) { |
| 12 | + int index = key % n; |
| 13 | + return (index > 0) ? (index) : (-index); |
| 14 | +} |
| 15 | + |
| 16 | +int calculate(struct HashNode **hashtable, int *length, int x, int n) { |
| 17 | + int index = hash(x, n); |
| 18 | + struct HashNode *p = hashtable[index]; |
| 19 | + while (p) { |
| 20 | + if (p->key == x) { /* if found */ |
| 21 | + if (length[p->value] == 1) { /* x' length hasn't been calculated */ |
| 22 | + length[p->value] = calculate(hashtable, length, x + 1, n) + 1; |
| 23 | + } |
| 24 | + return length[p->value]; |
| 25 | + } |
| 26 | + p = p->next; |
| 27 | + } |
| 28 | + return 0;/* not found */ |
| 29 | +} |
| 30 | + |
| 31 | +int longestConsecutive(int num[], int n) { |
| 32 | + int i; |
| 33 | + struct HashNode **hashtable |
| 34 | + = (struct HashNode **)calloc(n, sizeof(struct HashNode *)); |
| 35 | + |
| 36 | + for (i = 0; i < n; i++) { |
| 37 | + struct HashNode *new_node |
| 38 | + = (struct HashNode *)calloc(1, sizeof(struct HashNode)); |
| 39 | + new_node->key = num[i]; |
| 40 | + new_node->value = i; |
| 41 | + new_node->next = NULL; |
| 42 | + /* put new node into hash table */ |
| 43 | + int index = hash(num[i], n); |
| 44 | + struct HashNode **p = hashtable + index; |
| 45 | + /* get tail */ |
| 46 | + while (*p) { |
| 47 | + p = &(*p)->next; |
| 48 | + } |
| 49 | + *p = new_node; |
| 50 | + } |
| 51 | + |
| 52 | + int *length = (int *)malloc(n * sizeof(int)); |
| 53 | + /* set all elements' length to 1 */ |
| 54 | + for (i = 0; i < n; i++){ |
| 55 | + length[i] = 1; |
| 56 | + } |
| 57 | + |
| 58 | + /* try to calculate the length of num[i] recursively */ |
| 59 | + for (i = 0; i < n; i++) { |
| 60 | + if (length[i] > 1) continue; /* already calculated */ |
| 61 | + length[i] = calculate(hashtable, length, num[i] + 1, n) + 1; |
| 62 | + } |
| 63 | + |
| 64 | + int max_length = 1; |
| 65 | + for (i = 0; i < n; i++){ |
| 66 | + if (length[i] > max_length) |
| 67 | + max_length = length[i]; |
| 68 | + } |
| 69 | + return max_length; |
| 70 | +} |
| 71 | + |
| 72 | +int main() { |
| 73 | + int num1[] = { 100, 4, 200, 1, 3, 2 }; |
| 74 | + int num2[] = { 2, 3, 4, 5, 6, 7, 1 }; |
| 75 | + /* should be 4 */ |
| 76 | + printf("%d\n", longestConsecutive(num1, sizeof(num1) / sizeof(num1[0]))); |
| 77 | + /* should be 7 */ |
| 78 | + printf("%d\n", longestConsecutive(num2, sizeof(num2) / sizeof(num2[0]))); |
| 79 | + return 0; |
| 80 | +} |
0 commit comments