Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 矩阵的扩充数据结构_Arrays_Data Structures_Time Complexity - Fatal编程技术网

Arrays 矩阵的扩充数据结构

Arrays 矩阵的扩充数据结构,arrays,data-structures,time-complexity,Arrays,Data Structures,Time Complexity,给定一个大小为n的方阵(数据结构),其操作如下 read(i,j) returns the element write(i,j,x) write the new element initalize() set matrix to zero 读取和写入在(最坏情况)恒定时间内执行。 我如何扩展它,以便在(最坏情况)恒定时间内执行以下操作 emptyrow(i) if the ith row is empty then return true emptycol(j) if the jth col

给定一个大小为n的方阵(数据结构),其操作如下

read(i,j) returns the element
write(i,j,x) write the new element 
initalize() set matrix to zero
读取和写入在(最坏情况)恒定时间内执行。 我如何扩展它,以便在(最坏情况)恒定时间内执行以下操作

emptyrow(i) if the ith row is empty then return true
emptycol(j) if the jth col is empty then return true

我的第一个想法是,我不需要增加。我可以简单地使用for循环并读取(I,j)来得到结果,最坏的情况是常数时间n。我是否在正确的轨道上,或者我仍然需要以某种方式扩展数据结构。谢谢你的帮助

考虑将数据结构存储为条目的n×n矩阵,再加上两个额外的数组:一个rowCount数组,计算矩阵每行中有多少个1;一个colCount数组,包含数组每列中有多少个1

要执行initialize()操作,请创建矩阵和rowCount/colCount数组,并将所有内容初始化为0。这需要时间O(n2)。要执行读取(i,j),只需在时间O(1)中读取矩阵。要执行写入操作(i,j,x),请将x写入位置(i,j),如果将0更改为1或将1更改为0,请对rowCount和colCount数组进行适当的递增/递减。这也需要时间O(1)。最后,要执行emptyRow(i)或emptyCol(j),只需返回rowCount[i]或colCount[j]是否分别为零。这也需要时间O(1)

如果对所有操作都使用哈希表,并将“empty”表示为0,则可以加快构造O(1),尽管现在对剩余操作的保证是平均情况O(1),而不是最坏情况下的保证。视情况而定,这可能是一个很好的权衡