leetcode-594. 最长和谐子序列-C语言

该博客围绕LeetCode 594题,即最长和谐子序列展开,使用C语言进行求解。和谐子序列指最大值和最小值相差为1的子序列,此博客聚焦于用C语言找出最长的和谐子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int cmp(int *a, int *b){
    if(*a < *b){
        return -1;
    }else if(*a > *b){
        return 1;
    }
    return 0;
}

typedef struct nd{
    int val;
    int cnt;
} Node;

#define LEN 0xfffff

int findLHS(int* arr, int len){
 
    int i;
    int tmp, max = 0;
    Node table[LEN];
    int index = 0;
    
    if(!arr || !len) return 0;
    
    qsort(arr, len, sizeof(int), cmp);
    
    table[0].val = arr[0];
    table[0].cnt  = 1;
    
    for(i=1; i<len; i++){
        if(arr[i] == table[index].val){
            table[index].cnt++;
        }else{
            index++;
            table[index].val = arr[i];
            table[index].cnt = 1;
        }     
    }

    
    for(i=0; i<index; i++){
        if(table[i+1].val - table[i].val ==1 && table[i+1].cnt + table[i].cnt > max)
            max = table[i+1].cnt + table[i].cnt;
    }
    
    return max;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值