[LeetCode]303. Range Sum Query

来源:互联网 发布:sql语句计算平均值 编辑:程序博客网 时间:2024/06/11 17:03

题目描述:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
分析:根据给定的索引范围求和(动态规划)

解题思路:将0~n范围的数字求和,存入一维数组中。求索引i~j的和时只需要求得sum[j]-sum[i]
O(n) init O(1) query

public class Range_Sum_Query {    int sum[];    public Range_Sum_Query(int[] nums) {        if(nums!=null&&nums.length!=0){            sum = new int[nums.length];            sum[0] = nums[0];            for(int i=1;i<nums.length;i++){                sum[i] = sum[i-1]+nums[i];            }        }    }    public int sumRange(int i,int j){        if(i==0)return sum[j];        return sum[j]-sum[i-1];    }}
原创粉丝点击