【问题标题】:Return the count of negative numbers in the optimal way以最优方式返回负数的计数
【发布时间】:2013-07-20 11:31:06
【问题描述】:

“在按行和按列排序的矩阵中搜索”的变体

给定一个按行和按列排序的二维矩阵。您必须以最佳方式返回负数的计数。

我可以想到这个解决方案

  1. 初始化 rowindex=0

  2. 如果行索引>0 行索引++
    否则应用二分查找

并使用此代码实现 5X5 矩阵

#include<iostream>
#include<cstdio>
using namespace std;
int arr[5][5];

int func(int row)
{
    int hi=4;
    int lo=0;
    int mid=(lo+hi)/2;
    while(hi>=lo)
    {
        mid=(lo+hi)/2;
        .
        if(mid==4)
        {
            return 5;
        }
        if(arr[row][mid]<0 && arr[row][mid+1]<0)
        {
            lo=mid+1;
        }
        else if(arr[row][mid]>0 && arr[row][mid+1]>0)
        {
            hi=mid-1;
        }
        else if(arr[row][mid]<0 && arr[row][mid+1]>0)
        {
            return mid+1;
        }
    }
}

int main()
{
    int ri,ci,sum;
    ri=0;   //rowindex
    ci=0;   //columnindex
    sum=0;
    for(int i=0; i<5; i++)
    {
        for(int j=0; j<5; j++)
        {
            cin>>arr[i][j];
        }
    }
    while(ri<5)
    {
        if(arr[ri][ci]>=0)
        {
            ri++;
        }
        else if(arr[ri][ci]<0)
        {
            int p=func(ri);
            sum+=p;
            ri++;
        }
    }
    printf("%d\n",sum);
}

我在这里运行代码http://ideone.com/PIlNd2 x 行和 y 列的矩阵的运行时间 O(xlogy)

如果我在时间复杂度或代码实现方面有错误,请纠正我

有没有人有比这更好的想法来提高运行时复杂性?

【问题讨论】:

  • -ve 数表示小于零的数
  • 就说否定吧。
  • 不是很彻底。我们是否应该同等重视您的问题?
  • 抱歉先生,我会尽快添加更多细节
  • 在排序矩阵中搜索使用“左下”方法。复杂度:NxN 矩阵的 O(N)

标签: c++ algorithm multidimensional-array


【解决方案1】:

O(m+n) 算法,其中 m 和 n 是数组的维度,通过向下滑动负数部分的顶部来工作,找到每行中的最后一个负数。这很可能是 Prashant 在 cmets 中所说的:

int negativeCount(int m, int n, int **array) {
    // array is a pointer to m pointers to n ints each.
    int count = 0;
    int j = n-1;
    for (int i = 0, i < m; i++) {
        // Find the last negative number in row i, starting from the index of
        // the last negative number in row i-1 (or from n-1 when i==0).
        while (j >= 0 && array[i][j] >= 0) {
            j--;
        }
        if (j < 0) {
            return count;
        }
        count += j+1;
    }
    return count;
}

我们不能比最坏情况 O(m+n) 做得更好,但如果您期望的负数远少于 m+n,您可能会得到更好的通常情况时间。

假设你有一个 n × n 数组,其中array[i][j] &lt; 0 iff i &lt; n-j。在这种情况下,算法可以判断任何 i 的 array[i][n-1-i] &lt; 0 的唯一方法是查看该单元格。因此,该算法必须至少查看 n 个单元格。

【讨论】:

  • 如果这个算法的复杂度为 O(m+n),那么我的复杂度应该是 O(m+logn),如果我错了,请纠正我
  • @ankur:您对每一行进行二进制搜索,如果整个数组为负数,则需要 O(mlog(n)) 时间。此算法在某些特定行上花费的时间可能比您的要长,但它在线性搜索上花费的总时间是 O(n)。
  • 检测从右上角开始的第一个符号变化,向下滑动(当元素小于零然后row++,否则col--),这样可以跳过大部分矩阵部分。
  • 这里一定有错字。 i 和 j 都相对于n
  • @UmNyobe:确实如此。固定。
【解决方案2】:

您正在执行二分搜索。因此,您将 n 除以 2 以找到中点,然后继续除以,然后返回一个值。这看起来像一个二分搜索,即使您为每一行划分列。因此,您正在执行 O(log n)。或者像 O(x log n/y) 这样的东西。

【讨论】:

    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多