点击查看【bilibili】

image.png

时间复杂度

时间复杂度为O(1)的例子

  1. if(i==1)
  2. a=1 result =3+4 result =n*2 result=10000* 10000
  3. array.push('a') array.pop()
  4. map.set(1,1) map.get(1,1)

在计算复杂度的时候,O(1)一般会被忽略。但也有时间复杂度为O(1)的题

时间复杂度为O(n)的例子

for循环, while循环.(不使用二分搜索)
for(let i=O;i<n;i++)    let i=O; while(i<n)

let a = O;
for(let i=O;i<n;i++){
    a+=i;
}

时间复杂度为O(n2)的例子

嵌套for循环,嵌套while循环.
for(let i=0;i<n;i++){
    for(let j=0;j<n;j++){
        a+=i;
    }
}

时间复杂度为O(n)而非O(n2)
for(let i=0;i<n;i++){
}

for(let j=0;j<n;j++){
    a+=i;
}

时间复杂度为O(n)而非O(n2)
while(i<n){
    i++; j=i;
  while(j<n){
        i++;
    }
}

复杂度的计算

取复杂度最高的一项作为总体复杂度,前面的常数忽略

  1. n +n+1时间复杂度是n
  2. 2n+ 3n+ 6时间复杂度是n

    时间复杂度优化实例

    https://leetcode-cn.com/problems/two-sum/

    时间复杂度为O(log n)和O(n log n)

https://leetcode-cn.com/problems/two-sum/

  • 强制要求选择哪个复杂度

https://leetcode-cn.com/problems/set-matrix-zeroes/