Interval Sum
24%
Accepted
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
Have you met this question in a real interview? [start, end]
. For each query, calculate the sum number between index start and end in the given array, return the result list.
Yes
Example
For array
[1,2,7,8,5]
, and queries [(0,4),(1,2),(2,4)]
, return[23,9,20]
Note
Challenge
O(logN) time for each query
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
*/
public class Solution {
/**
*@param A, queries: Given an integer array and an query list
*@return: The result list
*/
public ArrayList<Long> intervalSum(int[] A,
ArrayList<Interval> queries) {
// write your code here
// write your code here
long[] preSum = new long[A.length];
long sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
preSum[i] = sum;
}
ArrayList<Long> res = new ArrayList<Long>();
for(int i = 0; i < queries.size(); i++){
res.add(preSum[queries.get(i).end] - preSum[queries.get(i).start] + A[queries.get(i).start]);
}
return res;
}
}
No comments:
Post a Comment