public class NumArray
    {
        List<int> list = new List<int>();
        public NumArray(int[] nums)
        {
            var sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                sum += nums[i];
                list.Add(sum);
            }
        }

        public int SumRange(int i, int j)
        {
            if (i == 0)
            {
                return list[j];
            }
            else
            {
                return list[j] - list[i - 1];
            }            
        }
    }

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.SumRange(i,j);
 */

https://leetcode.com/problems/range-sum-query-immutable/#/description

 

补充一个python的实现:

 1 from itertools import accumulate
 2 class NumArray:
 3 
 4     def __init__(self, nums: List[int]):
 5         self.dp = list(accumulate(nums))
 6         
 7     def sumRange(self, i: int, j: int) -> int:
 8         if i == 0:
 9             return self.dp[j]
10         else:
11             return self.dp[j] - self.dp[i-1]

 

posted on 2017-04-26 16:51  Sempron2800+  阅读(98)  评论(0编辑  收藏  举报