标签:dice new find fun i++ 复制 要求 imm tab
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
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
class NumArray { private final int[] arr; public NumArray(int[] nums) { this.arr = new int[nums.length]; int sum = 0; for(int i = 0; i < nums.length; i++){ sum += nums[i]; arr[i] = sum; } } public int sumRange(int i, int j) { return arr[j] - (i == 0 ? 0 : arr[i - 1]); } }
arr[i]是nums数组从0到i(包括)的sum,所以要求i,j之间的和,先判断i是否为0,然后等于arr[j] - arr[i - 1]。
以上是dp解法。
??倒是觉得easy题就要有easy题的亚子,直接设一个数组复制不就完了吗.
class NumArray { private final int[] arr; public NumArray(int[] nums) { arr = nums.clone(); } public int sumRange(int i, int j) { int res = 0; for(int m = i; i <= j; i++){ res += arr[i]; } return res; } }
303. Range Sum Query - Immutable
标签:dice new find fun i++ 复制 要求 imm tab
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11691017.html