![](/img/trans.png)
[英]Create a 2D array and initialize every element to be the value of i * j where i and j are the 2 indices (for instance, element [5][3] is 5 * 3 = 15)
[英]Java: Sum of 2D array where the M[i][j] = (int) i/j
T-測試用例數| 1 <= T <= 10和n-元素數| 1 <= n <= 1000000
例如
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
在這里很明顯,您不需要將值存儲在矩陣中,因為不可能分配那么多的空間( 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
列中, jth
元素的值會increased
,其中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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.