學渣帶你刷Leetcode0128最長連續序列

題目描述

給定一個未排序的整數數組,找出最長連續序列的長度。

要求算法的時間複雜度爲 O(n)。

示例:

輸入: [100, 4, 200, 1, 3, 2]
輸出: 4
解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度爲 4。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-consecutive-sequence
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

白話題目:
 

算法:

 

詳細解釋關注 B站  【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB

C語言完全代碼

int cmp(const void* a, const void* b)
{
    int pa = *(int *)a;
    int pb = *(int *)b;

    if (pa > pb) {
        return 1;
    } else if (pa = pb) {
        return 0;
    } else {
        return -1;
    }
}

int delmore(int* nums, int numsSize, int* buf) 
{
    int *p = nums;
    int *pb = buf + 1;
    int *q;
    int res = 1;

    int i = 1; 
    while (i < numsSize) {
        q = nums + i;
        if (*q != *p) {
            *pb = *q;
            p = q;
            pb++;
            res++;
        } 
        i++;
    }
    
    return res;
}

int longestConsecutive(int* nums, int numsSize){
    if (numsSize <= 1) {
        return numsSize;
    }

    int buf[numsSize];
    int bufsize = numsSize;
    
    qsort(nums, numsSize, sizeof(int), cmp);
    buf[0] = nums[0];
    bufsize = delmore(nums, numsSize, buf);
 
    int i = 1;
    int* p = buf;
    int* h = p;
    int* q = p + 1;
    int Maxlen = 1;

    while (i < bufsize) {
        if (*q != *p + 1) {
            h = q;
            p = q;
        } else {
            p++;            
        }
        q++;
        Maxlen = Maxlen > (q - h) ? Maxlen : (q - h);
        i++;
    }
     
    return Maxlen;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章