[LintCode] Interval Sum

338 查看

Problem

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]

Challenge

O(logN) time for each query

Note

很简单的题目,不过要达到O(logn)的时间,只能用前缀和的方法来做。

Solution

1. muggle法

public class Solution {
    public ArrayList<Long> intervalSum(int[] A, 
                                       ArrayList<Interval> queries) {
        ArrayList<Long> res = new ArrayList<Long> ();
        for (int i = 0; i < queries.size(); i++) {
            int start = queries.get(i).start;
            int end = queries.get(i).end;
            res.add(sum(A, start, end));
        }
        return res;
    }
    public long sum(int[] A, int start, int end) {
        long sum = 0;
        for (int i = start; i <= end; i++) {
            sum += A[i];
        }
        return sum;
    }
}


2. 前缀和法(推荐)

public class Solution {
    public ArrayList<Long> intervalSum(int[] A, 
                                       ArrayList<Interval> queries) {
        ArrayList<Long> res = new ArrayList<Long>();
        long[] preSum = new long[A.length];
        long sum = 0;
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
            preSum[i] = sum;
        }
        for (Interval i: queries) {
            if (i.start == 0) {
                res.add(preSum[i.end]);
            }
            else {
                res.add(preSum[i.end] - preSum[i.start-1]);
            }
        }
        return res;
    }
}