-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathIntervalSum.java
51 lines (46 loc) · 1.6 KB
/
IntervalSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* Given an integer array (index from 0 to n-1, where n is the size of this
* array), and an query list. Each query has two integers [start, end]. For
* each query, calculate the sum number between index start and end in the
* given array, return the result list.
Example
For array [1,2,7,8,5], and queries [(0,4),(1,2),(2,4)], return [23,9,20]
*/
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
*/
public class IntervalSum {
/**
*@param A, queries: Given an integer array and an query list
*@return: The result list
*/
public ArrayList<Long> intervalSum(int[] A, ArrayList<Interval> queries) {
ArrayList<Long> result = new ArrayList<Long>();
long[] sum = new long[A.length + 1];
for (int i = 0; i < A.length; ++i) {
sum[i + 1] = A[i] + sum[i];
}
for (Interval interval : queries) {
result.add(sum[interval.end + 1] - sum[interval.start]);
}
return result;
}
/*****************************************************************************/
public ArrayList<Long> intervalSum(int[] A, ArrayList<Interval> queries) {
ArrayList<Long> result = new ArrayList<Long>();
for (Interval interval : queries) {
long sum = 0;
for (int i = interval.start; i <= interval.end; ++i) {
sum += A[i];
}
result.add(sum);
}
return result;
}
}