LeetCode //C - 128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

Given an unsorted array of integers nums , return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints:

  • 0 < = n u m s . l e n g t h < = 1 0 5 0 <= nums.length <= 10^5 0<=nums.length<=105
  • − 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 −109<=nums[i]<=109

From: LeetCode

Link: 128. Longest Consecutive Sequence


Solution:

Ideas:

The idea behind this code is to find the length of the longest consecutive elements sequence in an unsorted array of integers. It does this by leveraging a hash table to achieve O(n) time complexity. Here's a step-by-step explanation of the code:

  1. Hash Table Creation: The code first creates a hash table to efficiently store and search for the numbers in the given array. The hash table is implemented using separate chaining, where each index in the table's array represents a linked list of hash nodes.

  2. Populating the Hash Table: The code iterates through the input array and inserts each number into the hash table. The key for each number is the number itself, and the index is calculated using the absolute value of the number modulo the table's size.

  3. Finding the Longest Consecutive Sequence: The main logic of the code iterates through the input array again, checking for the beginning of a consecutive sequence. It identifies the start of a sequence by looking for a number that doesn't have a predecessor (i.e., there's no (num - 1) in the hash table). Once the start of a sequence is found, it continues to check for consecutive numbers in the sequence, incrementing a counter for each successive number found.

  4. Checking for Consecutive Numbers: To check whether a number is part of a consecutive sequence, the code looks up the number in the hash table using the contains function. This enables efficient O(1) average-time lookups, allowing the code to quickly identify consecutive numbers in the sequence.

  5. Tracking the Longest Sequence: As the code identifies consecutive sequences, it keeps track of the length of the current sequence and updates the length of the longest sequence found so far. Once all numbers have been processed, the length of the longest consecutive sequence is returned.

  6. Memory Cleanup: Finally, the code includes logic to free the dynamically allocated memory for the hash table and its associated linked lists.

Code:
c 复制代码
struct HashNode {
    int key;
    struct HashNode *next;
};

struct HashTable {
    int size;
    struct HashNode **array;
};

struct HashTable* createHashTable(int size) {
    struct HashTable* table = (struct HashTable*)malloc(sizeof(struct HashTable));
    table->size = size;
    table->array = (struct HashNode**)malloc(sizeof(struct HashNode*) * size);
    for (int i = 0; i < size; i++) {
        table->array[i] = NULL;
    }
    return table;
}

void insert(struct HashTable *table, int key) {
    int index = (key < 0 ? -key : key) % table->size;
    struct HashNode *newNode = (struct HashNode*)malloc(sizeof(struct HashNode));
    newNode->key = key;
    newNode->next = table->array[index];
    table->array[index] = newNode;
}

bool contains(struct HashTable *table, int key) {
    int index = (key < 0 ? -key : key) % table->size;
    struct HashNode *current = table->array[index];
    while (current != NULL) {
        if (current->key == key) return true;
        current = current->next;
    }
    return false;
}

int longestConsecutive(int* nums, int numsSize) {
    if (numsSize == 0) return 0;

    struct HashTable *table = createHashTable(numsSize * 2);
    for (int i = 0; i < numsSize; i++) {
        insert(table, nums[i]);
    }

    int longestStreak = 0;
    for (int i = 0; i < numsSize; i++) {
        if (!contains(table, nums[i] - 1)) {
            int currentNum = nums[i];
            int currentStreak = 1;

            while (contains(table, currentNum + 1)) {
                currentNum += 1;
                currentStreak += 1;
            }

            if (currentStreak > longestStreak) {
                longestStreak = currentStreak;
            }
        }
    }

    // Free the allocated memory for the table
    for (int i = 0; i < table->size; i++) {
        struct HashNode* current = table->array[i];
        while (current != NULL) {
            struct HashNode* temp = current;
            current = current->next;
            free(temp);
        }
    }
    free(table->array);
    free(table);

    return longestStreak;
}
相关推荐
为什么这亚子1 小时前
九、Go语言快速入门之map
运维·开发语言·后端·算法·云原生·golang·云计算
1 小时前
开源竞争-数据驱动成长-11/05-大专生的思考
人工智能·笔记·学习·算法·机器学习
~yY…s<#>1 小时前
【刷题17】最小栈、栈的压入弹出、逆波兰表达式
c语言·数据结构·c++·算法·leetcode
幸运超级加倍~2 小时前
软件设计师-上午题-16 算法(4-5分)
笔记·算法
yannan201903132 小时前
【算法】(Python)动态规划
python·算法·动态规划
埃菲尔铁塔_CV算法2 小时前
人工智能图像算法:开启视觉新时代的钥匙
人工智能·算法
EasyCVR2 小时前
EHOME视频平台EasyCVR视频融合平台使用OBS进行RTMP推流,WebRTC播放出现抖动、卡顿如何解决?
人工智能·算法·ffmpeg·音视频·webrtc·监控视频接入
linsa_pursuer2 小时前
快乐数算法
算法·leetcode·职场和发展
小芒果_012 小时前
P11229 [CSP-J 2024] 小木棍
c++·算法·信息学奥赛
qq_434085902 小时前
Day 52 || 739. 每日温度 、 496.下一个更大元素 I 、503.下一个更大元素II
算法