常见的7种时间复杂度(Big O natoation):
O(1):Constant Complexity 常数复杂度
...
int n = 1000;
System.out.println("Hey - your input is:" +n);
...
int n = 1000;
System.out.println("Hey - your input is:"+n);
System.out.println("Hmm..I'm doing more stuff with:"+n);
System.out.println("And more:'+n);
...
O(log n):Logarithmic Complexity 对数复杂度
...
for(int i =1;i<=n;i = i *2)\
System.out.println("Hey - I'm busy looking at:"+i);
...
O(n):Linear Complexity线性时间复杂度
...
for(int i =1;i<=n;i++)
System.out.println("Hey - I'm busy looking at:"+i);
....
O(n^2):N square Complexity平方
...
for(int i =1;i<=n;i++){
for(int j =1;j<=n;j++)
System.out.println("Hey - I'm busy looking at:"+i+"and"+j);
}
...
O(n^3):N cubic Complexity立方
O(k^n):Exponential Growth指数
...
inf fib(int n){
if(n<2) return n;
return fib (n-1) + fib (n - 2);
}
...
O(n!):Factorial阶乘
...
递归
...
PS:只看最高复杂度的运算
主定理(Master Theorem):计算任何一个分治或递推关系时间复杂度的一个方法。
2分查找(binary search)
2叉树遍历(Binary tree traversal)
2维矩阵中2分查找(Optomal sorted matrix search)
归并排序(Merge sort)
常见时间复杂度的比较
O(1)<O(logn)<O(n)<O(nlogn)<O(n²)<O(n³)<O(2ⁿ)<O(n!)
空间复杂度
原则:
1.如果代码开了数组,则数组的长度基本上就是空间复杂度
2.如果有递归的话,则递归的最深深度及为空间复杂度
3.如果又有数组又有递归,则两者之间的最大值为空间复杂度