【力扣 - 最长连续数组】

题目描述

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。

示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

提示:

0 <= nums.length <= 10^5

-10^9 <= nums[i] <= 10^9

题解

思路

先排序再比较计数;
如果相邻两数差一计数,如果相等进入下一层循环判断;
如果后面数与前一个数既不相等又不比前一个多一,重值计数为1.

代码

int cmp(const void* a, const void* b)
{
    // Custom comparison function for qsort to sort integers in ascending order
    return (long long)*(int*)a - (long long)*(int*)b;
}

int longestConsecutive(int* a, int n)
{
    // Check for edge cases
    if (a == NULL || n == 0) {
        return 0;
    }
    
    /* The  qsort  function in C is used to sort an array in ascending order. 
     * It takes the following parameters: 
     * base: Pointer to the array to be sorted. 
     * nmemb: Number of elements in the array. 
     * size: Size in bytes of each element in the array. 
     * compar: Pointer to a comparison function that determines the order of elements. 
     * The comparison function ( compar ) should return an integer less than, 
     * equal to, or greater than zero if the first argument is considered to be 
     * respectively less than, equal to, or greater than the second argument. 
     * void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
     */
    // Sort the input array 'a' in ascending order
    qsort(a, n, sizeof(int), cmp);
    
    int t = a[0]; // Initialize 't' with the first element of the sorted array
    int cnt = 1; // Initialize 'cnt' to keep track of the current consecutive sequence length
    int max = 1; // Initialize 'max' to keep track of the maximum consecutive sequence length
    
    // Iterate through the sorted array to find the longest consecutive sequence
    for (int i = 1; i < n; i++) {
        if (a[i] == t) {
            // If the current element is equal to the previous element, skip it
            continue;
        } else if ((long long)a[i] - t == 1LL) {
            // If the current element is consecutive to the previous element
            t = a[i]; // Update 't' to the current element
            cnt++; // Increment the consecutive count
            if (max < cnt) {
                max = cnt; // Update 'max' if a longer consecutive sequence is found
            }
        } else {
            // If the current element is not consecutive to the previous element
            t = a[i]; // Update 't' to the current element
            cnt = 1; // Reset the consecutive count
        }
    }
    
    return max; // Return the maximum consecutive sequence length
}
### LeetCode 最长连续序列 Python 解法 #### 方法一:基于集合的线性时间复杂度算法 通过将输入数组转换为集合 `num_set`,可以快速判断某个数字是否存在。对于每个数字 `n`,如果其前驱 `n-1` 不在集合中,则尝试从当前数字向右扩展,直到找不到下一个连续数字为止。 以下是实现该方法的具体代码: ```python class Solution: def longestConsecutive(self, nums): num_set = set(nums) max_length = 0 for n in num_set: if n - 1 not in num_set: # 只有当不存在前驱时才开始计算 current_num = n current_streak = 1 while current_num + 1 in num_set: # 向右扩展 current_num += 1 current_streak += 1 max_length = max(max_length, current_streak) # 更新最大长度 return max_length ``` 这种方法的时间复杂度为 O(n),因为每个数字最多被访问两次(一次用于检查起点,另一次用于扩展)。空间复杂度也为 O(n)[^3]。 --- #### 方法二:动态规划与并查集优化 另一种思路是利用并查集来维护连通分量之间的关系。具体来说,可以通过查找父节点的方式合并相邻的区间,并记录每组的最大长度。 虽然此方法较为复杂,但在某些特定场景下可能更高效。以下是伪代码框架: ```python def union_find_longest_consecutive(nums): parent = {} def find(x): if parent[x] != x: parent[x] = find(parent[x]) return parent[x] def union(x, y): rootX = find(x) rootY = find(y) if rootX != rootY: parent[rootY] = rootX for num in nums: parent[num] = num if num - 1 in parent: union(num, num - 1) if num + 1 in parent: union(num, num + 1) count = collections.defaultdict(int) for num in parent.keys(): root = find(num) count[root] += 1 return max(count.values(), default=0) ``` 上述代码实现了基于并查集的方法,适合处理大规模数据集[^4]。 --- #### 测试案例分析 考虑测试用例 `[100, 4, 200, 1, 3, 2]` 的执行过程: 1. 将所有数字存入集合 `{100, 4, 200, 1, 3, 2}`。 2. 遍历集合中的每一个数字: - 对于 `100` 和 `200`,由于它们没有前驱,分别形成独立子序列 `[100]` 和 `[200]`。 - 对于 `1`,发现它可以扩展到 `[1, 2, 3, 4]`,因此更新最大长度为 4。 3. 返回最终结果 `4`。 这一逻辑完全符合题目描述的要求。 --- ### 结论 综上所述,最常用的解决方案是基于集合的操作方式,因为它简单易懂且性能优越。而并查集则适用于更加复杂的场景或者需要额外功能支持的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

六月悉茗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值