【问题标题】:Java: Sum of 2D array where the M[i][j] = (int) i/jJava:二维数组的总和,其中 M[i][j] = (int) i/j
【发布时间】:2017-04-26 05:37:16
【问题描述】:

T - 测试用例数 | 1

例如

if (T >= 1 && T <= 10) {
    for (int i = 0; i < T; i++) {
                int n = sc.nextInt();
                if (n > 0 && n <= 1000000) {
                    array = new int[n][n];
                    System.out.print("\n" + sumOfArray(array, n));
                }
             }
          }

需要求M[i][j]之和,其中M[i][j] = (int) i/j;

我已经编写了代码,但是对于 n>10000,我开始出现 OOM,(原因很明显)。

如果有人可以帮助我,那就太好了。需要一种全新的方法来解决问题。

例如。

Input   Output
2       
2       4
4       17

【问题讨论】:

  • i >=1 和 j>=1 .

标签: java arrays matrix sum 2d


【解决方案1】:

这里很明显,您不需要将值存储在矩阵中,因为不可能有那么多空间 (Array[10000][10000]) 可供分配。所以你需要以mathematical 的方式思考。

考虑一个4x4 矩阵并用i,j 表示每个元素。

1,1 1,2 1,3 1,4
2,1 2,2 2,3 2,4
3,1 3,2 3,3 3,4
4,1 4,2 4,3 4,4

现在我们可以在这里表示每个元素中存储的内容。

1/1 1/2 1/3 1/4   (In Integers)     1 0 0 0
2/1 2/2 2/3 2/4   ============>     2 1 0 0
3/1 3/2 3/3 3/4                     3 1 1 0
4/1 4/2 4/3 4/4                     4 2 1 1

通过将其分成列来处理此矩阵并求解每个columns。 对于第一列系列将是1+2+3+4。那么对于列号two(2),系列将是0+1+1+2

请注意,对于 ith 列,first i-1 的值为零,然后列中的 i values 相同。然后value 增加。同样,i 值也是一样的。再次增加1 等等。

所以在ith 列值中获取increased 上的jth 元素,其中j%i==0

因此,您可以在 1-D 数组中实现此逻辑,并且此方法的复杂度将为每个测试用例的 O(n logn)

代码:

import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);

        int testcases=sc.nextInt();

        while(testcases-- >0)
        {
            int n=sc.nextInt();

            long array[]=new long[n+1]; //Take long array to avoid overflow

            for(int i=1;i<=n;i++)
            {
                for(int j=i;j<=n;j+=i)
                {
                    array[j]++;          //This will store that which elements get increased
                                         //from zero how many times
                }
            }

            //Now we can do summation of all elements of array but we need to do prefix sum here

            long sum=0;
            for(int i=1;i<=n;i++)
            {  
                array[i]+=array[i-1];
                sum+=array[i];
            }

            System.out.println(sum);
        }
    }
}

【讨论】:

  • 谢谢桑克特。实际上是在同一条线上思考。得到了我想要的答案。
猜你喜欢
  • 1970-01-01
  • 2012-10-20
  • 2019-04-19
  • 1970-01-01
  • 2012-09-16
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多