LeetCode //C - 128. Longest Consecutive Sequence

这篇具有很好参考价值的文章主要介绍了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.文章来源地址https://www.toymoban.com/news/detail-649506.html

Code:
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;
}

到了这里,关于LeetCode //C - 128. Longest Consecutive Sequence的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【递增栈】个人练习-Leetcode-845. Longest Mountain in Array

    题目链接:https://leetcode.cn/problems/longest-mountain-in-array/ 题目大意:给出一个数组 arr[] ,定义【山数组】为【长度大于等于3】【前面部分递增,后面部分递减,存在一个山峰元素】的数组。求 arr[] 中的最长的是【山数组】的子列。 思路:递增栈当然可以,不过刚好想到另一个

    2024年02月06日
    浏览(41)
  • LeetCode 1048. Longest String Chain【记忆化搜索,动态规划,哈希表,字符串】中等

    本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,

    2024年02月05日
    浏览(33)
  • LeetCode128.最长连续序列

     我这个方法有点投机取巧了,题目说时间复杂度最多O(n),而我调用了Arrays.sort()方法,他的时间复杂度是n*log(n),但是AC了,这样的话这道题还是非常简单的,创建一个Hashmap,以nums数组的元素作为key,以这个元素是连续序列中的第几个作为value,先把数组排一下序,然后从第

    2024年02月12日
    浏览(22)
  • 【Leetcode】128.最长连续序列

    给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 示例1: 示例2: 提示 : 0 = nums.length = 10 5 -10 9 = nums[i] = 10 9

    2024年02月10日
    浏览(37)
  • leetcode做题笔记128. 最长连续序列

    给定一个未排序的整数数组  nums  ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。 请你设计并实现时间复杂度为  O(n)   的算法解决此问题。 本题要求最长连续序列,可以将先将数组内数先排序一遍,再向后不断遍历数组比较得到最长连续序列,但

    2024年02月09日
    浏览(31)
  • 代码随想录刷题第4天|LeetCode24、LeetCode19、LeetCode160、LeetCode142

    1、LeetCode24 两两交换链表中的节点 题目链接:24、两两交换链表中的节点 要想清楚终止条件,cur每次指向要交换的两个节点的前一个节点,cur = cur-next-next; 若链表元素个数为偶数 , 则最后时刻 cur-next = NULL; 若链表元素个数为奇数,则最后时刻 cur-next-next = NULL; 最后要返回

    2024年02月05日
    浏览(37)
  • 代码随想录刷题第6天|哈希表 LeetCode242、LeetCode349、LeetCode202、LeetCode1

    1、LeetCode242 有效的字母异位词 题目链接:242、有效的字母异位词 用哈希表,record[s[i]-\\\'a\\\']++,record[t[i]-\\\'a\\\']--,最后判断record里是否有元素不为0。 2、LeetCode349、两个数组的交集 题目链接:349、两个数组的交集 题目如果没有限制数值的大小,就无法使用数组来做哈希表。如果哈

    2024年02月06日
    浏览(49)
  • 《LeetCode》——LeetCode刷题日记

    本期,将给大家带来的是关于  LeetCode 的关于二叉树的题目讲解。 目录 (一)606. 根据二叉树创建字符串 💥题意分析  💥解题思路 (二)102. 二叉树的层序遍历 💥题意分析 💥解题思路 (三)236. 二叉树的最近公共祖先  💥题意分析 💥解题思路 首先,第一道题是关于

    2023年04月18日
    浏览(33)
  • 【LeetCode】《LeetCode 101》第六章:搜索

    深度优先搜索 和 广度优先搜索 是两种最常见的优先搜索方法,它们被广泛应用于图和树等结构中搜索。 深度优先搜索(depth-first search,DFS)在搜索到一个新的节点时,立即对该节点进行遍历;因此遍历需要用 先入后出 的栈实现,也可以用通过与栈等价的 递归 实现。 对于

    2023年04月09日
    浏览(59)
  • 【LeetCode周赛】LeetCode第370场周赛

    一场比赛中共有 n 支队伍,按从 0 到 n - 1 编号。 给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 = i, j = n - 1 且 i != j 的所有 i, j :如果 grid[i][j] == 1,那么 i 队比 j 队 强 ;否则,j 队比 i 队 强 。 在这场比赛中,如果不存在某支强于 a 队的队伍,则认为

    2024年02月05日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包