[英]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.