这是我的一道面试题。
我们有一个包含整数的矩阵(没有给出范围)。该矩阵随机填充整数。我们需要设计一个算法,找到与某列完全匹配的行。我们需要返回匹配的行号和列号。匹配元素的顺序是相同的。例如,如果第 i 行与第 j 列匹配,并且第 i 行包含元素 - [1,4,5,6,3]。那么第 j 列也将包含元素 - [1,4,5,6,3]。大小为 n x n。
我的解决方案:
RCEQUAL(A,i1..12,j1..j2)// A is n*n matrix
if(i2-i1==2 && j2-j1==2 && b[n*i1+1..n*i2] has [j1..j2])
use brute force to check if the rows and columns are same.
if (any rows and columns are same)
store the row and column numbers in b[1..n^2].//b[1],b[n+2],b[2n+3].. store row no,
// b[2..n+1] stores columns that
//match with row 1, b[n+3..2n+2]
//those that match with row 2,etc..
else
RCEQUAL(A,1..n/2,1..n/2);
RCEQUAL(A,n/2..n,1..n/2);
RCEQUAL(A,1..n/2,n/2..n);
RCEQUAL(A,n/2..n,n/2..n);
需要O(n^2)时间复杂度。如果正确,是否存在更快的算法?