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;
It will run in constant time i.e O(1) assuming board[M][N] to be a two dimensional array.
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.
O(1) - no iterations nor recursion.
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), i.e. linear complexity. If you double the size of n, you approximately double the execution time.
精彩评论