用于范围和查询的Java程序,无需更新
给定一个大小为 n 的整数数组 arr。我们需要计算从索引 i 到索引 j 的元素总和。由 i 和 j 索引值组成的查询将被执行多次。
例子:
Input : arr[] = {1, 2, 3, 4, 5}
i = 1, j = 3
i = 2, j = 4
Output : 9
12
Input : arr[] = {1, 2, 3, 4, 5}
i = 0, j = 4
i = 1, j = 2
Output : 15
5
// Java program to find sum between two indexes
// when there is no update.
import java.util.*;
import java.lang.*;
class GFG {
public static void preCompute(int arr[], int n, int pre[])
{
pre[0] = arr[0];
for (int i = 1; i < n; i++)
pre[i] = arr[i] + pre[i - 1];
}
// Returns sum of elements in arr[i..j]
// It is assumed that i <= j
public static int rangeSum(int i, int j, int pre[])
{
if (i == 0)
return pre[j];
return pre[j] - pre[i - 1];
}
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = arr.length;
int pre[] = new int[n];
preCompute(arr, n, pre);
System.out.println(rangeSum(1, 3, pre));
System.out.println(rangeSum(2, 4, pre));
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
输出:
9
12
有关更多详细信息,请参阅有关范围和查询的完整文章,无需更新!