簡體   English   中英

C 最長線算法

[英]C longest line algorithm

我想分析對副本 function 的調用次數的最佳和最差情況。 一般情況下會有什么困難? 請幫我理解這個解決方案?

我認為最好的情況是 1,最壞的情況是 n-1,對嗎?

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
 
int get_line(char line[], int maxline);
void copy(char to[], char from[]); 
 
/* print longest input line */
int main() 
{
int es;
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
es=0;
max = 0;
while ((len = get_line(line, MAXLINE)) > 0)
    if (len > max) 
    {
        es++;
        max = len;
        copy(longest, line);
    }
    printf("%d",es);
if (max> 0)  /* there was a line */
    printf("\nlongest is:%s\n", longest);
return 0;
}
 
/* get_line: read a line into s, return length */
int get_line(char s[], int lim)
{
int c, i;
 
 
for (i=0; i<lim-1 && (c=getchar()) !=EOF && c!='\n'; ++i)
    s[i] = c;
 
if (c == '\n')
{
    s[i] = c;
    ++i;
}
s[i] = '\0';
return i;
}
 
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i = 0;
while ((to[i] = from[i]) != '\0')
    ++i;
}

最佳案例

如果第一個get_line調用返回所有連續字符串中最長的字符串,則copy(longest, line)將僅執行一次。 對於這種情況,相對於copy的時間復雜度為 O(1)。

最壞的情況下

如果下一行比上一行長,則copy(longest, line)將被調用的次數與while循環中的迭代次數一樣多。 基本上,在這種情況下,時間復雜度為 O(n),其中 n - 迭代次數。

平均情況

這個比較棘手,我知道如何計算它的上限。 所以,我假設你的字符串的長度是均勻分布的並且都是不同的

因此,對於n次迭代,將有n不同的長度,因此n! 可能的排列。 對於一種情況,當第n次迭代達到最大值時,有(n-1)! 組合 -> 在n處達到最大值的概率是(n-1)!/n! = 1/n (n-1)!/n! = 1/n

現在,直到第n步達到最大值的次數是1 + 1/2 +... + 1/n ~ log(n) 如前所述,它是平均復雜度的上限,因為字符串的長度不一定是唯一的。

因此,相對於copy方法,時間復雜度為 O(log(n))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM