了解时间复杂度
问题描述:
有人可以帮助我理解下面代码的时间复杂性。该程序用于将所有的零移到数组的右侧。了解时间复杂度
class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String []s = br.readLine().split(" ");
int a[] = new int[s.length];
for(int i=0;i<s.length;i++)
a[i]=Integer.parseInt(s[i]);
int j= a.length-1;
int i=0;
while(j>=0 && i<a.length-1 && j-i>0){
if(a[i]==0){
while(a[j]==0)
j--;
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
i++;
}
for(int k:a)
System.out.print(k+" ");
}
}
答
计算时间复杂度将是困难的,如果我们试图包括a[i]=Integer.parseInt(s[i]);
自Integer class
,parseInt()
方法while loop
内运行,并根据通过字符串的长度,它会给出不同的时间复杂度,但如果我们假设它会花费O(F(q)),代码的时间复杂度将会是O(s.length^2)+O((s.length)*O(F(q))