[Java] 303. Regions and Retrieval-Immutable Arrays--Understand Java classes and learn constructors! ! !

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]))

Example:

Input:
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5] , [0, 5]]
Output:
[null, 1, -1, -3]

解释:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))

prompt:

0 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= i <= j < nums.length
最多调用 104 次 sumRange 方法

public class NumArray {
    
    
    private static int[] nums=null;
	public static void main(String[] args) {
    
    
		int[] nums= {
    
    -2, 0, 3, -5, 2, -1};
		NumArray numArray = new NumArray(nums);
		numArray.sumRange(0, 2);
		numArray.sumRange(2, 5); 
		numArray.sumRange(0, 5);	
	}
	public NumArray(int[] nums) {
    
    
        this.nums=nums;
    }    
    public int sumRange(int i, int j) {
    
    
    	int sum=0;
		for(int k=i;k<=j;k++) {
    
    
			sum+=this.nums[k];
		}
    	return sum;
    }
}

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114259783