简体   繁体   中英

Time Complexity of the following code..?

I am confused with the time complexity of the following piece of code....

i = 0

   //first row
   if(board[i][0] == win && board[i][1] == win && board[i][2] == win)
      return win;

   //second row
   if(board[i+1][0] == win && board[i+1][1] == win && board[i+1][2] == win)
      return win;

   //third row
   if(board[i+2][0] == win && board[i+2][1] == win && board[i+2][2] == win)
      return win;

   //first col
   if(board[0][i] == win && board[1][i] == win && board[1][i] == win)
      return win;

   //second col
   if(board[0][i+1] == win && board[1][i+1] == win && board[2][i+1] == win)
      return win;

   //third col
   if(board[0][i+2] == win && board[1][i+2] == win && board[2][i+2] == win)
      return win;

      //first diag
   if(board[i][i] == win && board[i+1][i+1] == win && board[i+2][i+2] == win)
      return win;

   //second diag
   if(board[i+2][i] == win && board[i+1][i+1] == win && board[i][i+2] == win)
      return win;

它将以固定时间运行,即假设board [M] [N]为二维数组,则为O(1)。

O(1)-无迭代也无递归。

This is obviously a trap question to see if you understood the concept of time complexity.

Time complexity measures the order of magnitude that an algorithm needs if applied to larger and larger input. Your example does depend only on a constant number of inputs, this why the others correctly said O(1). In essence this means that time complexity is not the correct tool to measure its efficiency, quality or whatsoever.

As the other answers suggest, it is O(1). But this is not considered as good coding practice. You can use a loop to generalize it.

As you've shown it there, it is O(1) because there are no variable facets to it. It will always take the same time to execute.

If you put it in a loop where i goes from 0 to n-1, then it will have O(n), ie linear complexity. If you double the size of n, you approximately double the execution time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM