|
| 1 | +## 303. 区域和检索 - 数组不可变 |
| 2 | +> https://leetcode-cn.com/problems/range-sum-query-immutable/ |
| 3 | +
|
| 4 | + |
| 5 | +### Java |
| 6 | +```java |
| 7 | +/* |
| 8 | + * @Author: Goog Tech |
| 9 | + * @Date: 2020-09-15 15:07:30 |
| 10 | + * @LastEditTime: 2020-09-15 15:11:43 |
| 11 | + * @Description: https://leetcode-cn.com/problems/range-sum-query-immutable/ |
| 12 | + * @FilePath: \leetcode-googtech\#303. Range Sum Query - Immutable\Solution.java |
| 13 | + * @Reference: https://leetcode-cn.com/problems/range-sum-query-immutable/solution/marveljian-dan-de-xue-xi-bi-ji-303-by-tyanyonecanc/ |
| 14 | + * @WebSite: https://algorithm.show/ |
| 15 | + */ |
| 16 | + |
| 17 | +class NumArray { |
| 18 | + |
| 19 | + private int[] sum; |
| 20 | + |
| 21 | + // DP : 动态规划 |
| 22 | + public NumArray(int[] nums) { |
| 23 | + sum = Arrays.copyOf(nums, nums.length); |
| 24 | + for(int i = 1; i < sum.length; i++) { |
| 25 | + // sum[i] 的值为 sum[0] 到 sum[i] 的所有值之和 |
| 26 | + sum[i] += sum[i - 1]; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public int sumRange(int i, int j) { |
| 31 | + return (i == 0) ? sum[j] : (sum[j] - sum[i - 1]); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * Your NumArray object will be instantiated and called as such: |
| 37 | + * NumArray obj = new NumArray(nums); |
| 38 | + * int param_1 = obj.sumRange(i,j); |
| 39 | + */ |
| 40 | +``` |
| 41 | + |
| 42 | +### Python |
| 43 | +```python |
| 44 | +''' |
| 45 | +Author: Goog Tech |
| 46 | +Date: 2020-09-15 15:07:34 |
| 47 | +LastEditTime: 2020-09-15 15:08:56 |
| 48 | +Description: https://leetcode-cn.com/problems/range-sum-query-immutable/ |
| 49 | +FilePath: \leetcode-googtech\#303. Range Sum Query - Immutable\Solution.py |
| 50 | +Reference: https://leetcode-cn.com/problems/range-sum-query-immutable/solution/marveljian-dan-de-xue-xi-bi-ji-303-by-tyanyonecanc/ |
| 51 | +WebSite: https://algorithm.show/ |
| 52 | +''' |
| 53 | + |
| 54 | +class NumArray(object): |
| 55 | + |
| 56 | + # DP : 动态规划 |
| 57 | + def __init__(self, nums): |
| 58 | + """ |
| 59 | + :type nums: List[int] |
| 60 | + """ |
| 61 | + if not nums: return |
| 62 | + self.result = [0] * len(nums) |
| 63 | + self.result[0] = nums[0] |
| 64 | + for i in range(1, len(nums)): |
| 65 | + # result[i] 的值为 nums[0] 到 nums[i] 的所有值之和 |
| 66 | + self.result[i] = self.result[i - 1] + nums[i] |
| 67 | + |
| 68 | + def sumRange(self, i, j): |
| 69 | + """ |
| 70 | + :type i: int |
| 71 | + :type j: int |
| 72 | + :rtype: int |
| 73 | + """ |
| 74 | + if i == 0: return self.result[j] |
| 75 | + else: return self.result[j] - self.result[i - 1] |
| 76 | + |
| 77 | +# Your NumArray object will be instantiated and called as such: |
| 78 | +# obj = NumArray(nums) |
| 79 | +# param_1 = obj.sumRange(i,j) |
| 80 | +``` |
0 commit comments