0
点赞
收藏
分享

微信扫一扫

最长的斐波那契子序列的长度-c语言哈希表解决(提升时间效率)

柠檬果然酸 2022-05-02 阅读 74

最长的斐波那契子序列的长度-c语言哈希表解决(提升时间效率)

如果序列 X_1, X_2, …, X_n 满足下列条件,就说它是 斐波那契式 的:

n >= 3
对于所有 i + 2 <= n,都有 X_i + X_{i+1} = X_{i+2}

给定一个严格递增的正整数数组形成序列 arr ,找到 arr 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。

(回想一下,子序列是从原序列 arr 中派生出来的,它从 arr 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8] 是 [3, 4, 5, 6, 7, 8] 的一个子序列)

示例 1:

输入: arr = [1,2,3,4,5,6,7,8]
输出: 5
解释: 最长的斐波那契式子序列为 [1,2,3,5,8] 。

示例 2:

输入: arr = [1,3,7,11,12,14,18]
输出: 3
解释: 最长的斐波那契式子序列有 [1,11,12]、[3,11,14] 以及 [7,11,18] 。

代码如下:

#define size 1000
struct hash{
    int key;
    struct hash * next;
};

 void hash_add( struct hash *h,int key){
    struct hash *hl=(struct hash *)malloc(sizeof(struct hash));
    hl->key=key;
    hl->next=h->next;
    h->next=hl;
  


}
void print_hash(struct hash * h){
    int i;
    struct hash *p;
    for(i=0;i<size;i++){
        p=(h+i)->next;
        
        while(p){
          printf("%d ",p->key);
            p=p->next;
        }
    }

}
int hash_find(struct hash * h,int key){
    struct hash *p=h->next;
    while(p){
        if(p->key==key){
            return 1;
        }
        p=p->next;
    }
    return 0;
}





int lenLongestFibSubseq(int* arr, int arrSize){
    struct hash *h=(struct hash *)malloc(sizeof(struct hash)*size);
    int i,j;
    int r[1000000];
    int t3;
    int t2;
    int t;
    int n;
    int p=0;

    for(i=0;i<size;i++){
        (h+i)->next=NULL;
    }
    for(i=0;i<arrSize;i++){
        hash_add(h+arr[i]%size,arr[i]);
    }
    //print_hash(h);
    for(i=0;i<arrSize-2;i++){
        for(j=i+1;j<arrSize-1;j++){
        
            t3=arr[i]+arr[j];
            t2=arr[j];
            n=0;
          ///  printf("t3 t2 %d %d ",t3,t2);

            while(hash_find(h+t3%size,t3)==1){
               
              t=t2;
               t2=t3;
               t3=t3+t;
        //         printf(" %d ",t3);
               n++;

            }
            r[p++]=n;

        }
    }
    int max=0;
    for(i=0;i<p;i++){
        if(r[i]>max){
            max=r[i];
        }
     //   printf("%d ",r[i]);
    }
    if(max==0) return 0;
    else return max+2;
   




}
举报

相关推荐

0 条评论