04 | complexity analysis (lower): Analysis of the best, worst, average, amortized time complexity

Best-case time complexity (best case time complexity), the worst case time complexity (worst case time complexity), where the average time complexity (average case time complexity), the time complexity is amortized (amortized time complexity). If you can grasp these concepts, it is for you, the complexity of the analysis of this section no big problem.

// n表示数组array的长度
int find(int[] array, int n, int x) {
  int i = 0;
  int pos = -1;
  for (; i < n; ++i) {
    if (array[i] == x) {
       pos = i;
       break;
    }
  }
  return pos;
}

 To find the x variables may appear anywhere in the array.

If the first element of the array is just a variable you want to find x, there is no need to continue to traverse the remaining n-1 data, that time complexity is O (1).

However, if the variable is not present in the array x, then we all need to traverse the entire array again, it would be time complexity O (n).

Therefore, under different circumstances, the time complexity of this code is not the same.

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/lakeslove/p/12313266.html