标签:
原题链接在这里:https://leetcode.com/problems/range-sum-query-immutable/
因为这个函数会被多次调用,每次都算一遍会花很多时间。
所以用dp数组来保存过去的值。dp[i] 表示 nums[0]到nums[i-1]的和,如此做是为了求sumRange时不需要额外讨论 i == 0的情况。
AC Java:
1 public class NumArray { 2 private int [] dp; 3 public NumArray(int[] nums) { 4 dp = new int[nums.length+1]; //dp[i]表示从nums[0]到nums[i-1]的和 5 for(int i = 1; i<=nums.length; i++){ 6 dp[i] = dp[i-1] + nums[i-1]; 7 } 8 } 9 10 public int sumRange(int i, int j) { 11 return dp[j+1] - dp[i]; 12 } 13 } 14 15 // Your NumArray object will be instantiated and called as such: 16 // NumArray numArray = new NumArray(nums); 17 // numArray.sumRange(0, 1); 18 // numArray.sumRange(1, 2);
LeetCode Range Sum Query - Immutable
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4961235.html