简体   繁体   English

代码复杂度分析

[英]Complexity analysis for code

so I wrote some Java code to list files in a directory and its sub-directories that were modified today. 所以我写了一些Java代码来列出目录及其子目录中的文件,这些文件今天已经被修改了。 I need a little help understanding the time and space complexity. 我需要一点帮助来了解时间和空间的复杂性。

The code: 编码:

public class FileInDir { 公共类FileInDir {

 File[] files = null; Date d = new Date(); long mill; public void listTodayFiles(String path) { File dir = new File(path); files = dir.listFiles(); for(File file : files){ mill = file.lastModified(); Date f = new Date(mill); if(f.getDate() == d.getDate()){ if(file.isFile()) System.out.println("FILE: " + file.getName() + " WAS LAST MODIFIED ON: " + f); else if(file.isDirectory()) listTodayFiles(file.getAbsolutePath()); } } } 

} }

So from what I understand, storing all the files into the array takes O(n) time, the loop takes O(n) time. 因此,据我了解,将所有文件存储到数组中需要O(n)时间,循环需要O(n)时间。 I'm unsure about the complexity for the recursive call. 我不确定递归调用的复杂性。 I'm also unsure if the if statement plays a role in time or space complexity. 我也不确定if语句是否在时间或空间复杂度中起作用。 Also will the space complexity be O(n) because it needs to store each element (file). 空间复杂度也将是O(n),因为它需要存储每个元素(文件)。

Thanks :D 感谢:D

Your complexity depends on what you choose for n. 您的复杂程度取决于您为n选择的内容。 If n is the number of files, the complexity is O(n) because each file is visited once. 如果n是文件数,则复杂度为O(n),因为每个文件被访问一次。

Time complexity as defined by @popovitsj is correct. @popovitsj定义的时间复杂度是正确的。

Your space complexity is also O(n) since you need to store each file object in the stack due to recursive calls. 您的空间复杂度也是O(n),因为由于递归调用而需要将每个文件对象存储在堆栈中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM