最好,最坏,平均,均摊时间复杂度

// 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;
  }
  return pos;
}

时间复杂度是O(n)

// 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;
}

最好是O(1),最坏是O(n)

平均时间复杂度如图:

猜你喜欢

转载自www.cnblogs.com/hanguocai/p/9900204.html
今日推荐