Skip to content

Latest commit

 

History

History
72 lines (57 loc) · 1.73 KB

time.md

File metadata and controls

72 lines (57 loc) · 1.73 KB

时间复杂度

表示算法的执行时间与数据规模之间的增长关系,常量可以忽略

  • O(1) 常数阶
  • O(n) 线性阶: 单层循环
  • O(n²) 平方阶: 两层循环
  • O(logn) 对数阶
// 当循环中下标以指定倍数形式衰减,那么这就是一个对数阶。
// 2^x=n
// x=log2n
public static void print2(int n){
    int i=1;
    while (i <= n) {
        i = i * 2;
    }
}
  • O(nlogn) 线性对数阶
// 嵌套代码的复杂度等于嵌套内外代码复杂度的乘积
for (int j=1;j<=n;j++){
    int i=1;
    while (i <= n) {
        i = i * 2;
    }
}
  • 指数阶,阶层阶,根号阶

  • 取最大复杂度作为整个算法复杂度 O(1)<O(n)<O(n²) -> O(n²)
  • 取多个复杂度之和作为整个算法复杂度 O(1),O(m),O(n) -> O(m+n)

时间复杂度类型

  • 最好时间复杂度
  • 最坏时间复杂度
  • 平均时间复杂度
  • 均摊时间复杂度
public static int findEle(int[] arr,int val){
        if (null == arr || arr.length == 0){
            return -1;
        }
       for (int i=0;i<arr.length;i++){
           if (arr[i] == val){
               return i;
           }
       }
       return -1;
    }
  • 最好时间复杂度 O(1)
  • 最坏时间复杂度 O(n)
  • 平均时间复杂度
    • 因为元素在数组中的概率为 1/2,然后在每个位置出现的概率也为 1/n。假如元素出现在第一个位置,复杂度为 1*(1/2n);假如元素出现在第二个位置,复杂度为 2 * (1/2n),最终得到当前场景下时间复杂度为:1*(1/2n) + 2 * (1/2n) + ... + n*(1/2n)=(n+1)/4。
    • 元素不存在数组中的 n * (1/2)
    • (n+1)/4 + n/2 = (3n+1)/4 = O(n)