Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.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
C++ 修改鞍形搜索以处理重复项_C++_C_Arrays_Algorithm_Data Structures - Fatal编程技术网

C++ 修改鞍形搜索以处理重复项

C++ 修改鞍形搜索以处理重复项,c++,c,arrays,algorithm,data-structures,C++,C,Arrays,Algorithm,Data Structures,我知道鞍式搜索算法在O(n)时间内可以在排序的2d数组中找到一个元素(数组按X维和Y维排序)(或者称之为排序的2d方形矩阵),并且没有重复项。从我读过的所有文章来看,它似乎是二维平方排序矩阵的最佳算法。对于那些不知道鞍形算法如何工作的人: 将二维阵列想象为二维矩阵 1. Start at the top-left corner. i.e.  Initialize row to its maximum value and column to its minimum value. 2. Check

我知道鞍式搜索算法O(n)时间内可以在排序的2d数组中找到一个元素(数组按X维和Y维排序)(或者称之为排序的2d方形矩阵),并且没有重复项。从我读过的所有文章来看,它似乎是二维平方排序矩阵的最佳算法。对于那些不知道鞍形算法如何工作的人:

将二维阵列想象为二维矩阵

1. Start at the top-left corner. i.e.  Initialize row to its maximum value and column to its minimum value.
2. Check at (row, column). If it’s value is less than the target value, then increase column by one.
3. If it's greater than the target value, then decrease row by one. 
4. Do this until we reach the element or boundary
示例:

在下面的2d排序数组中查找54

现在,我如何以有效的方式修改此算法,以搜索二维排序数组中可能有重复项的元素的所有出现次数。 示例: 在下面的数组中查找54的所有出现


您可以如下递归地重用算法。在索引
(i,j)
中找到目标值后,您希望对两个子矩阵再次执行算法:
M[i+1:M,j]
M[i:M,j+1:n]
。第一种情况很简单,因为它是一个单列,并且您知道所有/任何引用都位于该列的顶部。一旦在该列中有了所有引用,您就可以对子矩阵
M[i:M,j+1:n]
应用完全相同的算法,即严格地在找到的位置的右侧和其行或行下方的值

当矩阵中的每个值都是目标值时,您可以在问题中做的最好和最坏的情况发生,从而导致O(m*n)比较。这个递归版本可以做到这一点,它的性能通常是O(m+n+x),其中x是共享一列的出现次数

伪代码:

// assume M is non-ascending going down (+rows) and non-descending going right (+cols)
findOccurrences(Matrix M, Value target) {
    (List of Pair of int and int) result = {}
    int i, j = 0
    while( i < M.rows && j < M.cols )
        if( M[i, j] < target )
            j = j + 1
        else if( M[i, j] > target )
            i = i + 1
        else
            int k = i
            while( k < M.rows && M[k, j] == target )
                result.append({k, j})
                k = k + 1
            // we have found all occurrences in column j
            // there may be any number of occurrences left
            // in the submatrix to the right of i,j but
            // below or at i so just continue with the next j
            j = j + 1
    return result
}
//假设M是非升序向下(+行)和非降序向右(+列)
findOccurrences(矩阵M,价值目标){
(int和int对的列表)结果={}
int i,j=0
而(i目标)
i=i+1
其他的
int k=i
而(k
找到引用后,尝试按降序进行,直到找到不同的值。接下来,从发生点开始向上移动,当值不同时停止。如果在中间34值处着陆,则向左移动,直到没有更多的34。这是起点。一直往前走,直到没有更多的人了。这是终点。由于矩阵是按定义排序的,因此所有相同的值将放在一起,除非矩阵没有重复项。否则,请澄清“搜索所有事件”的含义。您的第二个图形显示算法执行错误。@游戏:对。你能找出如何追踪一大块54的上下轮廓吗?这是唯一缺少的成分。@ThomasMatthews:“搜索所有事件”我的意思是说查找所有(x,y),其中arr[x,y]=54