我试图弄清楚这段代码的时间复杂性,作为我的任务的一部分。代码如下所示:
public int solvePuzzle( )
{
searchAlg = BINARY_SEARCH ? new BinarySearch() : new LinearSearch();
int matches = 0;
for( int r = 0; r < rows; r++ )
for( int c = 0; c < columns; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
searchAlg.printStatistics();
return matches;
}
此方法使用Binary Search
或Linear Search
。
我的任务要求我在T(M,N) = O(?)
中找到时间复杂度,其中M是排序字典的大小,将使用线性二进制搜索进行搜索,N是&#34的大小;拼图&#34; (char [] [])其中两个数组(行和列= N =相同大小)。
这部分matches += solveDirection( r, c, rd, cd );
使用二进制/线性搜索来搜索已排序的数组。
到目前为止,这是我提出的。
二进制搜索的时间复杂度为Log M
线性搜索的时间复杂度为M
前两个for-loop
的时间复杂度均为N.
但是第3和第4个循环的时间复杂度是什么,T(M,N)
等于什么?
第4循环的3r是O(3)吗?这是否意味着T(M,N)= O(M * N * N * 3 * 3)/ O(logM * N * N * 3 * 3)?
任何帮助都会受到赞赏。
编辑:solveDirection()
的代码:
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta )
{
String charSequence = "";
int numMatches = 0;
int searchResult;
charSequence += theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < rows && j < columns;
i += rowDelta, j += colDelta )
{
charSequence += theBoard[ i ][ j ];
if ( charSequence.length() > maxWordLength )
break;
searchResult = searchAlg.search( theWords, charSequence );
if( searchResult == theWords.length ) { // corrected by UH 2007-05-02
// either linear searched failed or binary search failed because charSequence
// is larger than the largest word in theWords
if ( searchAlg instanceof BinarySearch )
break; // binary search failed and it makes no sense to extend charSequence any further
else
continue; // linear search failed but an extension of charSequence may succeed
}
// precondition: 0 <= searchResult < theWords.length
// At this point one, and only one, of three conditions holds:
// 1. Linear search succeeded
// 2. Binary search succeded
// 3. Binary search failed at the insertion point for charSequence,
// which means that theWords[ searchResult ] is the least element greater than charSequence
if( PREFIX_TESTING && ! theWords[ searchResult ].startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) ) {
// if( theWords[ searchResult ].length( ) < 2 )
// continue;
numMatches++;
if ( PRINT_WORDS )
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " + i + " " + j );
}
}
return numMatches;
}
答案 0 :(得分:2)
你走在正确的轨道上。
然而,关键的洞察力是O( k )= O(1)对于任何常数 k (=与输入的大小无关)。因此,您的O( N · N ·3·3)与O( N · N )。而且这个结果需要与你已经正确完成的搜索相乘。