Regions and retrieval-immutable arrays
Title description: Given an integer array nums, find the sum of the elements in the range from index i to j (i ≤ j), including two points i and j.
Implement the NumArray class:
- NumArray(int[] nums) uses the array nums to initialize the object
- int sumRange(int i, int j) returns the sum of the elements in the array nums from index i to j (i ≤ j), including two points i and j (that is, sum(nums[i], nums[i + 1] , ..., nums[j]))
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/range-sum-query-immutable/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Accumulate
First, declare an int array type member variable numsNumArray
sumRange
the method 0614ab153c1733 is to add the element values at positionleft~right
package com.kaesar.leetcode;
public class LeetCode_303 {
public static void main(String[] args) {
// 测试用例
NumArray numArray = new NumArray(new int[]{-2, 0, 3, -5, 2, -1});
System.out.println(numArray.sumRange(0, 2)); // return 1 ((-2) + 0 + 3)
System.out.println(numArray.sumRange(2, 5)); // return -1 (3 + (-5) + 2 + (-1))
System.out.println(numArray.sumRange(0, 5)); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
}
}
class NumArray {
private int[] nums;
public NumArray(int[] nums) {
this.nums = nums;
}
public int sumRange(int left, int right) {
int result = 0;
for (int i = left; i <= right; i++) {
result += nums[i];
}
return result;
}
[Daily Message] in the morning, let the mood fly in the sun, face the unknown, be brave and fearless; let the happy heart follow, relaxed and bright.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。